Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a multiple in Swift?

Tags:

swift

I am trying to find the odd numbers and a multiple of 7 between a 1 to 100 and append them into an array. I have got this far:

var results: [Int] = []
for n in 1...100 {
    if n / 2 != 0 && 7 / 100 == 0 {
        results.append(n)
    }
}
like image 317
user2167323 Avatar asked Oct 26 '15 12:10

user2167323


3 Answers

Your conditions are incorrect. You want to use "modular arithmetic"

Odd numbers are not divisible by 2. To check this use:

if n % 2 != 0

The % is the mod function and it returns the remainder of the division (e.g. 5 / 2 is 2.5 but integers don't have decimals, so the integer result is 2 with a remainder of 1 and 5 / 2 => 2 and 5 % 2 => 1)

To check if it's divisible by 7, use the same principle:

if n % 7 == 0

The remainder is 0 if the dividend is divisible by the divisor. The complete if condition is:

if n % 2 != 0 && n % 7 == 0

You can also use n % 2 == 1 because the remainder is always 1. The result of any mod function, a % b, is always between 0 and b - 1.

Or, using the new function isMultiple(of:, that final condition would be:

if !n.isMultiple(of: 2) && n.isMultiple(of: 7)
like image 197
Arc676 Avatar answered Oct 28 '22 21:10

Arc676


Swift 5:

Since Swift 5 has been released, you could use isMultiple(of:) method.

In your case, you should check if it is not multiple of ... :

if !n.isMultiple(of: 2)
like image 42
Ahmad F Avatar answered Oct 28 '22 19:10

Ahmad F


Swift 5 is coming with isMultiple(of:) method for integers , so you can try

let res = Array(1...100).filter { !$0.isMultiple(of:2) && $0.isMultiple(of:7) }
like image 28
Sh_Khan Avatar answered Oct 28 '22 19:10

Sh_Khan