Project Euler #1: Multiples of 3 and 5 | Hackerrank | Project Euler

Multiple of 3 and 5 


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

1<=T<=10^5
1<=T<=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:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int t;
    long int s3,s5,s15,f3,f5,f15; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){
        long int sum=0,n;
        scanf("%ld",&n);
        f3=(n-1)/3;
        f5=(n-1)/5;
        f15=(n-1)/15;
        s3=3*((f3*(f3+1))/2);
        s5=5*((f5*(f5+1))/2);
        s15=15*((f15*(f15+1))/2);
        sum=s5+s3-s15;
        printf("%ld\n",sum);
    }
    return 0;
}

You can also run it on an online IDE:   


Your feedback are always welcome! If you have any doubt you can contact me or leave a comment!  Happy Coding !! Cheers!!!


Related Links:


No comments:

Post a Comment

Super Market Problem | TCS Code Vita 2023 - Zone 1 | Super Market TCS Code Vita 2023 Solution | Code Vita 2023 | Code Vita 2023 season 11 solution

 Problem Description: In a Super market we will find many variations of the same product. In the same way we can find many types of rice bag...