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)
}
}
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)
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)
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With