PROBLEM

Project Euler #1: Multiples of 3 and 5 Solution

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below N.

Input Format

First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.

Constraints

  • ≤ T ≤ 10^5
  • 1 ≤ N ≤ 10^9

Output Format

For each test case, print an integer that denotes the sum of all the multiples of 3  or 5 below N.

Sample Input 0

2
10
100

Sample Output 0

23
2318

Explanation 0

For N = 10, if we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Similarly for N = 100, we get 2318.


Solution In Java-15

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static long ans(long n){
        //n * (n - 1)/2
        long three = 0, first = 0, five = 0, second = 0, extra = 0, third = 0;
        if(n%3 == 0){
            three = n/3;
            first = 3*((three * (three - 1))/2);
        }else{
            three = n/3;
            first = 3*((three * (three + 1))/2);
        }

        if(n%5 == 0){
            five = n/5;
            second = 5*((five * (five - 1))/2);
        }else{
            five = n/5;
            second = 5*((five * (five + 1))/2);
        }

         if(n%15 == 0){
            extra = n/15;
            third = 15*((extra * (extra - 1))/2);
        }else{
            extra = n/15;
            third = 15*((extra * (extra + 1))/2);
        }
        
        

        return first + second - third;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            long n = in.nextLong();
            System.out.println(ans(n));
        }
    }
}

Happy Coding . 

Project Euler #1: Multiples of 3 and 5 Solution
If You Want The Explanation Of This Problem, Feel Free To Contact Me .


With This Here I'm Providing The Required JavaScript Code For Project Euler #1: Multiples of 3 and 5 Solution

JavaScript Solution :-

function solution(n) {

   var r = n / 3 | 0;
   var s = n / 5 | 0;
   var t = n / 15 | 0;

   return 3 * r * ++r + 5 * s * ++s - 15 * t * ++t >> 1;
}
console.log(solution(999));

Play This On Replit . You Can Also Follow Me (Pabitra Banerjee) To Show Your Support.