How to find the sum of all the multiples of 3 or 5 below 1000 in Swift

2 Answers

0 votes
import Foundation

func sumOfMultiples(limit: Int) -> Int {
    var sum = 0

    // Iterate through numbers from 0 to 999
    for x in 0..<limit {
        if x % 3 == 0 || x % 5 == 0 {
            sum += x
        }
    }

    return sum
}

// Define the limit
let limit = 1000

// Calculate and print the result
print(sumOfMultiples(limit: limit))




/*
run:

233168

*/

 



answered Apr 15 by avibootz
0 votes
import Foundation

func sumOfMultiples(limit: Int) -> Int {
    // Calculate the upper bounds
    let upperForThree = limit / 3
    let upperForFive = limit / 5
    let upperForFifteen = limit / 15

    // Calculate the sums using the arithmetic series formula
    let sumThree = 3 * upperForThree * (1 + upperForThree) / 2
    let sumFive = 5 * upperForFive * (1 + upperForFive) / 2
    let sumFifteen = 15 * upperForFifteen * (1 + upperForFifteen) / 2

    // Calculate the total sum
    return sumThree + sumFive - sumFifteen
}

// Define the limit
let limit = 999

// Calculate and print the result
print(sumOfMultiples(limit: limit))




/*
run:

233168

*/

 



answered Apr 15 by avibootz
...