Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.programming > #1613
| From | "H.J. Sander Bruggink" <sander.bruggink@uni-due.de> |
|---|---|
| Newsgroups | comp.programming |
| Subject | Re: Project Euler - add all natural numbers below 1000 |
| Date | 2012-05-23 14:11 +0200 |
| Message-ID | <a242erF8c7U1@mid.dfncis.de> (permalink) |
| References | <4fbcc3ed$0$283$14726298@news.sunsite.dk> |
On 05/23/2012 01:03 PM, arnuld wrote:
> AIM: To write a program to add all natural numbers below 1000 that are
> multiples of 3 or 5.
>
> WHAT I GOT: it works
Does it? How did you test it?
Let's test it with a limit of 16 instead of 1000. What is the correct
answer? I suspect you want it to be
3 + 5 + 6 + 9 + 10 + 12 + 15 = 60
but the output of your program is 75 because it will add 15 twice (it is
a multiple of both 3 and 5).
>
> Question-1: Look at the for loop, instead of looping for 1000 times and
> checking the value inside, I am simply looping it 1000/3 = 333 times. Ist
> that impressive ?
>
> Question-2: Can it be improved ?
Yes, programs that don't work can always be improved.
>
>
>
> /* Add all the natural numbers below one thousand that are multiples of 3
> or 5. */
>
> #include<stdio.h>
> #include<stdlib.h>
>
> int main(void)
> {
> const int limit = 7;
I suspect you mean limit = 1000;
> const int multiple_A = 3;
> const int multiple_B = 5;
> unsigned long sum;
> int i, j;
> sum = 0;
>
> for(i = 0, j = 0; (i<= limit); i = i + multiple_A, j = j + multiple_B)
> {
> printf("i = %d, j = %d\n", i, j);
> if(j<= limit)
> {
> sum = sum + i + j;
> }
> else
> {
> sum = sum + i;
> }
> }
>
> printf("Sum = %lu\n", sum);
>
> return 0;
> }
>
regards,
Sander
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