I am new to competitive programming and I did a problem on Hacker Rank. The question statement is as follows:
"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.
Output Format For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N."
Constraints
1≤T≤10^5
1≤N≤10^9
I've written the following code which successfully satisfies 3 test cases and fails at remaining 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 is the mistake in my code. Why isn't it getting accepted?
There are a couple of issues.
You are indeed overflowing your int
when returning from func
. Also, your printf
statement should be printf("%llu\n", count);
So, the return from func
, count
, and the local variable j
, should all be unsigned long long
and your print out should reflect that as well. You need to make j
unsigned long long
because of the arithmetic in the return statement for func
(this is at least the case in VS 2013).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With