We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
u'll face time complexity O(n) (meaning the iterations times depends on the input , if the output is too large so will be the time to process it which could outrun the given limit time) if you run the typical chcking each i (i%3==0 or i%5==0) , here's a simlpe script in c to fix this issue
include
long long sum_multiples(int n, int k) {
long long m = (n - 1) / k;
return k * m * (m + 1) / 2;
}
int main() {
int t;
scanf("%d", &t);
for (int a0 = 0; a0 < t; a0++) {
int n;
scanf("%d", &n);
long long sum = sum_multiples(n, 3) + sum_multiples(n, 5) - sum_multiples(n, 15);
printf("%lld\n", sum);
}
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #1: Multiples of 3 and 5
You are viewing a single comment's thread. Return to all comments →
u'll face time complexity O(n) (meaning the iterations times depends on the input , if the output is too large so will be the time to process it which could outrun the given limit time) if you run the typical chcking each i (i%3==0 or i%5==0) , here's a simlpe script in c to fix this issue
include
long long sum_multiples(int n, int k) { long long m = (n - 1) / k; return k * m * (m + 1) / 2; }
int main() { int t; scanf("%d", &t); for (int a0 = 0; a0 < t; a0++) { int n; scanf("%d", &n); long long sum = sum_multiples(n, 3) + sum_multiples(n, 5) - sum_multiples(n, 15); printf("%lld\n", sum); } return 0; }