Sum of all the multiples of 3 or 5 below 1000 gives a wrong answer in C
Project Euler problem:
If we list all the natural numbers below
10
that are multiples of3 or 5
, we get3, 5, 6 and 9
. The sum of these multiples is23
.
Find the sum of all the multiples of
3 or 5
below1000
.
My C code:
long int x;
long int y;
long int z = 0;
long int a = 0;
long int b = 0;
for(x= 0; x < 1000; x += 3)
a = a + x;
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
return 0;
But I'm getting 266333
as the output which is wrong. I checked the answer with Python and I got it right. I would like to know what I'm doing wrong with the C code. The right answer is 233168
My Python code:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
c
add a comment |
Project Euler problem:
If we list all the natural numbers below
10
that are multiples of3 or 5
, we get3, 5, 6 and 9
. The sum of these multiples is23
.
Find the sum of all the multiples of
3 or 5
below1000
.
My C code:
long int x;
long int y;
long int z = 0;
long int a = 0;
long int b = 0;
for(x= 0; x < 1000; x += 3)
a = a + x;
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
return 0;
But I'm getting 266333
as the output which is wrong. I checked the answer with Python and I got it right. I would like to know what I'm doing wrong with the C code. The right answer is 233168
My Python code:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
c
1
%lu
should be%ld
– Spikatrix
Jul 25 '18 at 6:37
7
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
1
Exactly what @SanderDeDycker said. Merge the twofor
loops into one. Or don't add numbers that are multiples of 3 in the second loop
– Spikatrix
Jul 25 '18 at 6:43
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57
add a comment |
Project Euler problem:
If we list all the natural numbers below
10
that are multiples of3 or 5
, we get3, 5, 6 and 9
. The sum of these multiples is23
.
Find the sum of all the multiples of
3 or 5
below1000
.
My C code:
long int x;
long int y;
long int z = 0;
long int a = 0;
long int b = 0;
for(x= 0; x < 1000; x += 3)
a = a + x;
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
return 0;
But I'm getting 266333
as the output which is wrong. I checked the answer with Python and I got it right. I would like to know what I'm doing wrong with the C code. The right answer is 233168
My Python code:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
c
Project Euler problem:
If we list all the natural numbers below
10
that are multiples of3 or 5
, we get3, 5, 6 and 9
. The sum of these multiples is23
.
Find the sum of all the multiples of
3 or 5
below1000
.
My C code:
long int x;
long int y;
long int z = 0;
long int a = 0;
long int b = 0;
for(x= 0; x < 1000; x += 3)
a = a + x;
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
return 0;
But I'm getting 266333
as the output which is wrong. I checked the answer with Python and I got it right. I would like to know what I'm doing wrong with the C code. The right answer is 233168
My Python code:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
c
c
edited Jul 25 '18 at 6:47


Spikatrix
17.5k62761
17.5k62761
asked Jul 25 '18 at 6:28
RaheefRaheef
33
33
1
%lu
should be%ld
– Spikatrix
Jul 25 '18 at 6:37
7
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
1
Exactly what @SanderDeDycker said. Merge the twofor
loops into one. Or don't add numbers that are multiples of 3 in the second loop
– Spikatrix
Jul 25 '18 at 6:43
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57
add a comment |
1
%lu
should be%ld
– Spikatrix
Jul 25 '18 at 6:37
7
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
1
Exactly what @SanderDeDycker said. Merge the twofor
loops into one. Or don't add numbers that are multiples of 3 in the second loop
– Spikatrix
Jul 25 '18 at 6:43
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57
1
1
%lu
should be %ld
– Spikatrix
Jul 25 '18 at 6:37
%lu
should be %ld
– Spikatrix
Jul 25 '18 at 6:37
7
7
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
1
1
Exactly what @SanderDeDycker said. Merge the two
for
loops into one. Or don't add numbers that are multiples of 3 in the second loop– Spikatrix
Jul 25 '18 at 6:43
Exactly what @SanderDeDycker said. Merge the two
for
loops into one. Or don't add numbers that are multiples of 3 in the second loop– Spikatrix
Jul 25 '18 at 6:43
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57
add a comment |
6 Answers
6
active
oldest
votes
Some numbers will be divisible by both 3 and 5, you should not add them twice.
A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if
make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use
Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say thatcontinue
is a good thing to do for that x)
– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
|
show 1 more comment
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + *n**F*)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of sums of 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ldn", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
add a comment |
What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.
A slight modification to the code will do the trick.
for(x= 0; x < 1000; x += 3)
{
if(x%5)
{
a = a + x;
}
}
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
add a comment |
Direct translation of your python code:
#include <stdio.h>
int main(int argc, char *argv)
{
int sum = 0;
for (int x = 0; x < 1000; x++)
{
if (x % 5 == 0 || x % 3 == 0)
sum += x;
}
printf("%d", sum);
}
add a comment |
For the fun of it, I decided on giving the problem some additional constraints.
- The loop iterator can not take values that aren't a multiple
- The numbers must be added to the sum in numerical order.
int sum_multiples(long int m1,long int m2,long int lim)
{
long int sum=0;
for(long int i=m1;i<lim;i=((i+m1)/m1)*m1>((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
return sum;
}
int main(int argc, char *argv)
{
printf("Total: %ld n",sum_multiples(3,5,1000));
return 0;
}
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
add a comment |
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include <stdio.h>
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ldn", calc(3,5,n));
return 0;
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51512180%2fsum-of-all-the-multiples-of-3-or-5-below-1000-gives-a-wrong-answer-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Some numbers will be divisible by both 3 and 5, you should not add them twice.
A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if
make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use
Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say thatcontinue
is a good thing to do for that x)
– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
|
show 1 more comment
Some numbers will be divisible by both 3 and 5, you should not add them twice.
A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if
make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use
Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say thatcontinue
is a good thing to do for that x)
– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
|
show 1 more comment
Some numbers will be divisible by both 3 and 5, you should not add them twice.
A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if
make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use
Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);
Some numbers will be divisible by both 3 and 5, you should not add them twice.
A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if
make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use
Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);
edited Aug 6 '18 at 7:27
answered Jul 25 '18 at 6:51


RizwanRizwan
1,596419
1,596419
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say thatcontinue
is a good thing to do for that x)
– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
|
show 1 more comment
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say thatcontinue
is a good thing to do for that x)
– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
However here it using %lu in place of %ld here not make much diff. Still I am accepting your suggestion. %ld should be used for long. And %lu for unsigned long.
– Rizwan
Jul 25 '18 at 7:21
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
You don't need continue to make sure that if number is divisible by 3 it will not be tested for divisible by 5... An else if do the same job and better...
– Aryboo
Jul 25 '18 at 7:23
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
@Aryboo - accepted. But already mentioned even more optimized way just below the code.
– Rizwan
Jul 25 '18 at 7:25
Indeed but don't say that
continue
is a good thing to do for that x)– Aryboo
Jul 25 '18 at 7:26
Indeed but don't say that
continue
is a good thing to do for that x)– Aryboo
Jul 25 '18 at 7:26
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
@Aryboo - Accepted your suggestion and edited it appropriately. Thanks :)
– Rizwan
Jul 25 '18 at 7:32
|
show 1 more comment
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + *n**F*)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of sums of 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ldn", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
add a comment |
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + *n**F*)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of sums of 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ldn", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
add a comment |
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + *n**F*)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of sums of 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ldn", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + *n**F*)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of sums of 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ldn", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
edited Jul 25 '18 at 12:30
answered Jul 25 '18 at 12:24
Eric PostpischilEric Postpischil
74k879160
74k879160
add a comment |
add a comment |
What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.
A slight modification to the code will do the trick.
for(x= 0; x < 1000; x += 3)
{
if(x%5)
{
a = a + x;
}
}
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
add a comment |
What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.
A slight modification to the code will do the trick.
for(x= 0; x < 1000; x += 3)
{
if(x%5)
{
a = a + x;
}
}
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
add a comment |
What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.
A slight modification to the code will do the trick.
for(x= 0; x < 1000; x += 3)
{
if(x%5)
{
a = a + x;
}
}
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.
A slight modification to the code will do the trick.
for(x= 0; x < 1000; x += 3)
{
if(x%5)
{
a = a + x;
}
}
for(y = 0; y < 1000; y += 5)
b = b + y;
z = a + b;
printf("%lu", z);
answered Jul 25 '18 at 6:53
Amal JohnAmal John
5915
5915
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
add a comment |
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
It would be ever so slightly more performant to do the modulo check on the +5 loop instead of the +3. (200 vs 333 modulo branches)
– visibleman
Jul 25 '18 at 7:07
1
1
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
Yes adding the if the the +5 loop is optimal Thanks ;)
– Amal John
Jul 25 '18 at 7:49
add a comment |
Direct translation of your python code:
#include <stdio.h>
int main(int argc, char *argv)
{
int sum = 0;
for (int x = 0; x < 1000; x++)
{
if (x % 5 == 0 || x % 3 == 0)
sum += x;
}
printf("%d", sum);
}
add a comment |
Direct translation of your python code:
#include <stdio.h>
int main(int argc, char *argv)
{
int sum = 0;
for (int x = 0; x < 1000; x++)
{
if (x % 5 == 0 || x % 3 == 0)
sum += x;
}
printf("%d", sum);
}
add a comment |
Direct translation of your python code:
#include <stdio.h>
int main(int argc, char *argv)
{
int sum = 0;
for (int x = 0; x < 1000; x++)
{
if (x % 5 == 0 || x % 3 == 0)
sum += x;
}
printf("%d", sum);
}
Direct translation of your python code:
#include <stdio.h>
int main(int argc, char *argv)
{
int sum = 0;
for (int x = 0; x < 1000; x++)
{
if (x % 5 == 0 || x % 3 == 0)
sum += x;
}
printf("%d", sum);
}
edited Jul 25 '18 at 11:55


chux
82.6k872149
82.6k872149
answered Jul 25 '18 at 6:58
JabberwockyJabberwocky
26.7k93770
26.7k93770
add a comment |
add a comment |
For the fun of it, I decided on giving the problem some additional constraints.
- The loop iterator can not take values that aren't a multiple
- The numbers must be added to the sum in numerical order.
int sum_multiples(long int m1,long int m2,long int lim)
{
long int sum=0;
for(long int i=m1;i<lim;i=((i+m1)/m1)*m1>((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
return sum;
}
int main(int argc, char *argv)
{
printf("Total: %ld n",sum_multiples(3,5,1000));
return 0;
}
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
add a comment |
For the fun of it, I decided on giving the problem some additional constraints.
- The loop iterator can not take values that aren't a multiple
- The numbers must be added to the sum in numerical order.
int sum_multiples(long int m1,long int m2,long int lim)
{
long int sum=0;
for(long int i=m1;i<lim;i=((i+m1)/m1)*m1>((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
return sum;
}
int main(int argc, char *argv)
{
printf("Total: %ld n",sum_multiples(3,5,1000));
return 0;
}
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
add a comment |
For the fun of it, I decided on giving the problem some additional constraints.
- The loop iterator can not take values that aren't a multiple
- The numbers must be added to the sum in numerical order.
int sum_multiples(long int m1,long int m2,long int lim)
{
long int sum=0;
for(long int i=m1;i<lim;i=((i+m1)/m1)*m1>((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
return sum;
}
int main(int argc, char *argv)
{
printf("Total: %ld n",sum_multiples(3,5,1000));
return 0;
}
For the fun of it, I decided on giving the problem some additional constraints.
- The loop iterator can not take values that aren't a multiple
- The numbers must be added to the sum in numerical order.
int sum_multiples(long int m1,long int m2,long int lim)
{
long int sum=0;
for(long int i=m1;i<lim;i=((i+m1)/m1)*m1>((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
return sum;
}
int main(int argc, char *argv)
{
printf("Total: %ld n",sum_multiples(3,5,1000));
return 0;
}
edited Jul 25 '18 at 12:04
Jabberwocky
26.7k93770
26.7k93770
answered Jul 25 '18 at 9:56


visiblemanvisibleman
1,459819
1,459819
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
add a comment |
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
Thanks for the edit @Jabberwocky , I couldn't figure out how to get the code block to work after a bullet list. The horizontal line apparently will do the trick.
– visibleman
Jul 26 '18 at 0:41
add a comment |
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include <stdio.h>
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ldn", calc(3,5,n));
return 0;
}
add a comment |
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include <stdio.h>
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ldn", calc(3,5,n));
return 0;
}
add a comment |
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include <stdio.h>
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ldn", calc(3,5,n));
return 0;
}
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include <stdio.h>
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ldn", calc(3,5,n));
return 0;
}
edited Nov 21 '18 at 5:05
answered Nov 21 '18 at 1:16


TigerTV.ruTigerTV.ru
7801621
7801621
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51512180%2fsum-of-all-the-multiples-of-3-or-5-below-1000-gives-a-wrong-answer-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
%lu
should be%ld
– Spikatrix
Jul 25 '18 at 6:37
7
some numbers are divisible by both 3 and 5 (eg. 15) - you should not add them twice !
– Sander De Dycker
Jul 25 '18 at 6:43
1
Exactly what @SanderDeDycker said. Merge the two
for
loops into one. Or don't add numbers that are multiples of 3 in the second loop– Spikatrix
Jul 25 '18 at 6:43
Thank You Guys!! that was very helpful
– Raheef
Jul 25 '18 at 6:49
Note: To solve "Sum of all the multiples of A or B below N", a loop is not needed.
– chux
Jul 25 '18 at 11:57