Euler Q1 C++ code
kinuthiA muchanE
muchanek at gmail.com
Wed Jul 23 09:38:23 BST 2008
Eric,
Firstly, I think you are using an old version of c++, but that would not
prevent you from getting the correct answer ;). Secondly, the mistake
you are making is that you are incrementing sum twice, the question is
if an integer is a multiple of 3 OR 5. So, if you modify the condition
in the "while" loop to:
<code>
if (n%3 == 0 || n%5 == 0) {
sum += n;
}
</code>
... all should work well. The reason it is working with 10 is because
you are iterating over very few numbers, but as size of the number
increases things change!:-)
Does this help?
Kinuthia...
On Wed, 2008-07-23 at 09:41 +0300, Eric Kivuti wrote:
> This email is from a ubuntu-ke subscriber to other subscribers inluding you:)
> This is the code I used (cpp attachment available):
>
> 0 mod 3 = 0
> 1 mod 3 = 1
> 2 mod 3 = 2
> 3 mod 3 = 0
>
> so for all x mod 3 = 0
> */
> #include <iostream.h>
> void main(){
> int n=1, sum=0;
> while (n<10){
> if((n%3)==0){
> cout<<n<<", ";
> sum+=n;
> }
> if((n%5)==0){
> cout<<n<<", ";
> sum+=n;
> }
> n++;
> }cout<<"\n\nsum = "<<sum<<endl;
> }
>
> Output:
>
> 3, 5, 6, 9
>
> Sum = 23
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: https://lists.ubuntu.com/archives/ubuntu-ke/attachments/20080723/ca95320a/attachment.htm
> -------------- next part --------------
> An embedded and charset-unspecified text was scrubbed...
> Name: question_1.cpp
> Url: https://lists.ubuntu.com/archives/ubuntu-ke/attachments/20080723/ca95320a/attachment.diff
More information about the Ubuntu-ke
mailing list