Hacker Rating: Project Euler # 1

I am new to competitive programming, and I made a problem with Hacker Rank. The question request is as follows:

"If we list all 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 multiples of 3 or 5 below N.

Input format The first line contains T, which indicates the number of test cases. This is followed by T lines, each of which contains an integer, N.

Output Format For each test case, print an integer that indicates the sum of all multiples of 3 or 5 below N.

Limitations

1≤T≤10 ^ 5

1≤N≤10 ^ 9

I wrote the following code that successfully satisfies 3 test cases and does not work with the other two.

#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int func(int p,int n) { int j; n=n-1; j=n/p; return (p*j*(j+1))/2; } int main() { unsigned long int n; int t,j,count; scanf("%d",&t); if(t>=1 && t<=100000){ for(j=0;j<t;j++) { scanf("%lu",&n); if(n>=1 && n<=1000000000) { count=func(3,n)+func(5,n)-func(15,n); printf("%d\n",count); } }} return 0; } 

What a mistake in my code. Why is it not accepted?

+5
source share
1 answer

There are several issues.

You really overflow your int when returning from func . In addition, your printf statement should be printf("%llu\n", count);

So, the return from func , count and the local variable j should be unsigned long long , and your fingerprint should also reflect that. You have to make j unsigned long long due to arithmetic in the return statement for func (this at least applies to VS 2013).

+1
source

Source: https://habr.com/ru/post/1214763/


All Articles