Find the sum of multiples of 3 or 5 below N.
Formula: 3*(N/3)*(N/3+1)/2+5*(N/5)*(N/5+1)/2-15*(N/15)*(N/15+1)/2
Example 1:
Input : n=10 Output: 23 //3+5+6+9 = 23
Approach:
Java
public class Multiplesof3and5 {
public static void main(String[] args) {
int n = 100;
int sum = multiplierOfSUM(n);
System.out.println("Sum is " + sum);
}
// method for find sum of multiples of 3 and 5
private static int multiplierOfSUM(int n) {
n = n - 1;
int ans = 0;
int three = n / 3;
int five = n / 5;
int fifteen = n / 15;
ans = ans + three * (three + 1) / 2 * 3;
ans = ans + five * (five + 1) / 2 * 5;
ans = ans - fifteen * (fifteen + 1) / 2 * 15;
return ans;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=10;
n=n-1;
int ans=0;
int three=n/3;
int five=n/5;
int fifteen=n/15;
ans=ans+three*(three+1)/2*3;
ans=ans+five*(five+1)/2*5;
ans=ans-fifteen*(fifteen+1)/2*15;
cout<<ans<<"\n";
return 0;
}
No comments:
Post a Comment