Find the sum(integer) of all the multiples of 3 or 5 below N. I have used the normal AP series formula for this calculation...but two of the test cases are coming wrong.Anyone can tell me whats wrong with this code? I have not used loop that that shows termination due to timeout
int T = sc.nextInt();
double f1 =0;
double f2 =0;
double f3 =0;
double sum =0;
for(int i =0; i<T; i++){
int n = sc.nextInt();
// n1,n2,n3 are the number of multiples
int n1 = (n-1)/3;
int n2 = (n-1)/5;
int n3 = (n-1)/15;
// summation formula of AP series
f1 = (n1/2.0)*(6+(n1-1)*3);
f2 = (n2/2.0)*(10+(n2-1)*5);
f3 = (n3/2.0)*(30+(n3-1)*15);
// summation multiples of 3 OR 5
sum = f1-f3+f2;
// Printing the final integer
System.out.println((int)sum);
}
}
}
private int Sum(int N) {
int sum = 0;
for (int i = 3; i < N; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.