Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Ike Naar Newsgroups: comp.programming Subject: Re: Project Euler - add all natural numbers below 1000 Date: Wed, 23 May 2012 13:55:11 +0000 (UTC) Organization: A noiseless patient Spider Lines: 47 Message-ID: References: <4fbcc3ed$0$283$14726298@news.sunsite.dk> <4fbcdbbd$0$283$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Injection-Date: Wed, 23 May 2012 13:55:11 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="mX321DN/BskaPeu9dpMNqQ"; logging-data="23398"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+UNu0sCQOJ4m732Q9L4xUM" User-Agent: slrn/0.9.9p1 (NetBSD) Cancel-Lock: sha1:n5s1dF2QsTlWZEmW7hXPSNGdcuE= Xref: csiph.com comp.programming:1615 On 2012-05-23, arnuld wrote: > /* Add all the natural numbers below one thousand that are multiples of 3 > or 5. > * version 0.1 > */ > > #include > #include > > 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 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; }