Wednesday, 14 December 2022

Task and Solution in Java : Project Euler #1: Multiples of 3 and 5 (HackerRank)

 

This problem is a programming version of Problem 1 from projecteuler.net

If we list all the natural numbers below  that are multiples of  or , we get  and . The sum of these multiples is .

Find the sum of all the multiples of  or  below .

Input Format

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

Constraints

Output Format

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

Sample Input 0

2
10
100

Sample Output 0

23
2318

Explanation 0

For , if we list all the natural numbers below  that are multiples of  or , we get  and . The sum of these multiples is .

Similarly for , we get .


Solution 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;



public class Multiples_of_3_and_5 {
     // this method gives sum of n terms in AP talking first term
    // as 'a' and common differnce as d and number of terms as n
    static long apSum(long a, long d, long n){
        long ans = a*n + n*(n-1)*d/2 ;
        return ans;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for(int i = 0; i < t; i++){
            long n = sc.nextLong();
            n = n - 1; // we need to find below n so decrement n by 1
            // number of terms which are less than n and divisible by 3 are n/3
            // similarly number of terms divisible by 5 below n are n/5
            // so we find AP Sum of 3 and 5 and remove sum for 15 as 15 comes in common for 3 and 5
            System.out.println(apSum(3,3, n/3) + apSum(5,5, n/5) - apSum(15, 15, n/15));
        }
        sc.close();

    }
}


Source : HackerRank

No comments:

Post a Comment