Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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

2 Answers

0 votes
fun main() {
    var sum = 0

    // Iterate through numbers from 0 to 999
    for (x in 0 until 1000) {
        if (x % 3 == 0 || x % 5 == 0) {
            sum += x
        }
    }

    println(sum)
}

   
      
/*
run:

233168
  
*/

 



answered Apr 15, 2025 by avibootz
0 votes
fun main() {
    // Define the limit
    val limit = 999

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

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

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

    println(totalSum)
}

   
      
/*
run:

233168
  
*/

 



answered Apr 15, 2025 by avibootz
...