Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.programming > #1615
| From | Ike Naar <ike@sverige.freeshell.org> |
|---|---|
| Newsgroups | comp.programming |
| Subject | Re: Project Euler - add all natural numbers below 1000 |
| Date | 2012-05-23 13:55 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <slrn3vfsjrpr1v.l2l.ike@sverige.freeshell.org> (permalink) |
| References | <4fbcc3ed$0$283$14726298@news.sunsite.dk> <a242erF8c7U1@mid.dfncis.de> <4fbcdbbd$0$283$14726298@news.sunsite.dk> |
On 2012-05-23, arnuld <sunrise@invalid.address> wrote:
> /* Add all the natural numbers below one thousand that are multiples of 3
> or 5.
> * version 0.1
> */
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main(void)
> {
> int i;
> unsigned long s = 0;
>
> for (i = 3; i <= 1000; i += 3)
Nit: < 1000 (you want to add only numbers *below* 1000).
Here it does not matter because 1000 is not a multiple of 3,
but if you would change the limit to something that *is* a
multiple of 3, you'd get a wrong answer.
> s += i;
>
> for (i = 5; i < 1000; i += 5)
> {
> if(i % 3) s += i;
> }
>
> printf("%lu\n", s);
>
> return EXIT_SUCCESS;
> }
Just for fun, here's an alternative program, without loops.
#include <stdio.h>
int main(void)
{
long const n = 1000;
long const n3 = (n-1) / 3;
long const n5 = (n-1) / 5;
long const n15 = (n-1) / 15;
long const sum = (3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1)) / 2;
printf("%ld\n", sum);
return 0;
}
Back to comp.programming | Previous | Next — Previous in thread | Next in thread | Find similar
Project Euler - add all natural numbers below 1000 arnuld <sunrise@invalid.address> - 2012-05-23 11:03 +0000
Re: Project Euler - add all natural numbers below 1000 Bjoern Hoehrmann <bjoern@hoehrmann.de> - 2012-05-23 13:30 +0200
Re: Project Euler - add all natural numbers below 1000 "H.J. Sander Bruggink" <sander.bruggink@uni-due.de> - 2012-05-23 14:11 +0200
Re: Project Euler - add all natural numbers below 1000 arnuld <sunrise@invalid.address> - 2012-05-23 12:44 +0000
Re: Project Euler - add all natural numbers below 1000 Ike Naar <ike@sverige.freeshell.org> - 2012-05-23 13:55 +0000
Re: Project Euler - add all natural numbers below 1000 bob <bob@coolfone.comze.com> - 2012-05-23 06:56 -0700
Re: Project Euler - add all natural numbers below 1000 jt@toerring.de (Jens Thoms Toerring) - 2012-05-25 09:29 +0000
Re: Project Euler - add all natural numbers below 1000 bob <bob@coolfone.comze.com> - 2012-05-25 06:26 -0700
Re: Project Euler - add all natural numbers below 1000 jt@toerring.de (Jens Thoms Toerring) - 2012-05-26 21:52 +0000
Re: Project Euler - add all natural numbers below 1000 "BartC" <bc@freeuk.com> - 2012-05-27 01:52 +0100
csiph-web