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

2 Answers

0 votes
package main

import (
    "fmt"
)

func main() {
    sum := 0

    // Iterate through numbers from 0 to 999
    for x := 0; x < 1000; x++ {
        if x % 3 == 0 || x % 5 == 0 {
            sum += x
        }
    }

    fmt.Println(sum)
}




/*
run:

233168

*/

 



answered Apr 14, 2025 by avibootz
0 votes
package main

import (
    "fmt"
)

func main() {
    // Define the limit
    limit := 999

    // Calculate the upper bounds
    upperForThree := limit / 3
    upperForFive := limit / 5
    upperForFifteen := limit / 15

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

    // Calculate the total sum
    totalSum := sumThree + sumFive - sumFifteen

    fmt.Println(totalSum)
}




/*
run:

233168

*/

 



answered Apr 14, 2025 by avibootz
...