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

2 Answers

0 votes
function sumOfMultiples(limit: number): number {
    let sum: number = 0;

    // Iterate through numbers from 0 to limit - 1
    for (let x: number = 0; x < limit; x++) {
        if (x % 3 === 0 || x % 5 === 0) {
            sum += x;
        }
    }

    return sum;
}

// Define the limit
const limit: number = 1000;

// Calculate and print the result
console.log(sumOfMultiples(limit));


   
   
/*
run:
  
233168 
   
*/

 



answered Apr 15 by avibootz
0 votes
function sumOfMultiples(limit: number): number {
    // Calculate the upper bounds
    const upperForThree: number = Math.floor(limit / 3);
    const upperForFive: number = Math.floor(limit / 5);
    const upperForFifteen: number = Math.floor(limit / 15);

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

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

// Define the limit
const limit: number = 999;

// Calculate and print the result
console.log(sumOfMultiples(limit));


   
   
/*
run:
  
233168 
   
*/

 



answered Apr 15 by avibootz
...