Reputation: 2387
Below is my swift function to calculate the sum of multiples of a given set of real numbers in a range from 0 to 'upto'. The algorithm loops through from 1 to the upper limit and maps the array of multiples to an array of modulos for the specified multipliers and then reduces that array using multiplication such that if a given value of i is evenly divisible by any of the given multipliers the result of the reduce will be 0.
func sumOfMultiples(mults: [Int], upto: Int) -> {
var acc: Int = 0
for i in 1...upto {
if mults.map({i % $0}).reduce(1,*) == 0 {
acc += i
}
}
return acc
}
The problem is I'm getting a compile error
error: 'Int' is not a subtype of '()'
if mults.map({i % 0}).reduce(1,*) == 0 {
Upvotes: 0
Views: 162
Reputation: 13316
// Methinks you're missing this: ~~~~~~~~vvv
func sumOfMultiples(mults: [Int], upto: Int) -> Int {
Upvotes: 1
Reputation: 2387
func sumOfMultiples(mults: [Int], upto: Int) -> {
var acc: Int = 0
for i in 1...upto {
if mults.map( { (x) in i % x } ).reduce(1,*) == 0 {
acc += i
}
}
return acc
}
Upvotes: 0