-1

How do I find all the numbers divisible by another number in swift that have a remainder of 0? This is a Fizzbuzz related question.

Lets say that...

let number = 150

And I want to do something like...

print("Fizz") // for all the numbers where the remainder of number % 3 == 0.

So if number was 15, it would print "Fizz" 5 times.

4 Answers4

0

This will work

let number = 150

for num in 1...number {
    if num % 3 == 0 {
        print("Fizz :\(num)")
    }
}
Khundragpan
  • 1,952
  • 1
  • 14
  • 22
-1

you can just loop through the number and check with your desired divisible number if the remainder is 0 then print fizz

let number = 15

for i in 0..<number {
    if i % 3 == 0 {
        print("\(i) Fizz")
    }
}

It will print Fizz 5 times with the i value, that which number is Fizz.

Bhautik Ziniya
  • 1,554
  • 12
  • 19
-1

Simply try this code: (You can simply replace num with any Int number and divider that is also an Int value which is used to divide all numbers till num. )

override func viewDidLoad() { 
      let num:Int = 15
      let divider:Int = 3
      var counter:Int = divider
      while counter <= num {
         print("Fizz")
         counter += divider
      }
  }
Ashvini
  • 342
  • 3
  • 11
-1
func fizzbuzz(number: Int) -> String {
    if number % 3 == 0 && number % 5 == 0 {
        return "Fizz Buzz"
    } else if number % 3 == 0 {
        return "Fizz"
    } else if number % 5 == 0 {
        return "Buzz"
    } else {
        return String(number)
    }
}

https://www.hackingwithswift.com/guide/ios-classic/1/3/challenge

Mr.Javed Multani
  • 12,549
  • 4
  • 53
  • 52