Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello.

I'm trying to solve problem 6 at the project euler site, but I'm having trouble.

This is my code so far:

JavaScript
var square = 0;
var sum = 0;
var result = 0;

for (var i = 0; i < 101; i++){
    square = Math.pow(i, 2);
    square += square;
    
    sum += i;
}

result = Math.pow(sum, 2) - square;
console.log(result);


As I see it, the for loop starts counting and increasing i, the variable "square" first takes the power of i and then adds it to itself. It does that again and again so the final result should be all the numbers from 1 to 100 each to the power of 2. After that the variable "sum" counts all the numbers from 1 to 100 and stores them in itself. After that, the variable "result" takes "sum" to the power of 2 and substracts "sum" from "square". This seems pretty logical in my head, but apparently something's wrong as I get the wrong result (25482500).

Can someone please explain to me what I did wrong?
Posted

1 solution

Um...Look at your code:
C#
for (var i = 0; i < 101; i++){
    square = Math.pow(i, 2);
    square += square;

    sum += i;
}
What value is in square after the loop?
Answer: 20,000
Why?
Because it only ever uses the final value to go round the loop: 100 - all other values are discarded the next time it goes round the loop.
And 100 * 100 * 2 == 20,000

You need to start using the debugger to work this kind of thing out, rather that asking other people!
 
Share this answer
 
Comments
Leo Chapiro 24-Sep-15 7:09am    
Ah, I see it, you mean he needs to write instead

for (var i = 0; i < 101; i++){
square += Math.pow(i, 2);
sum += i;
}
?

BTW, +5 ! :)
OriginalGriff 24-Sep-15 7:24am    
Probably - but without seeing exactly what "problem 6 at the project euler site" wants him to do, I can't be sure. And I'm not randomly looking for a matching site...:laugh:
Member 12008365 24-Sep-15 7:55am    
It's in the name. The PROJECT EULER website. https://projecteuler.net/problem=6

Also, the suggested solution by _duDE_ is not the correct solution. It gives the wrong answer.
Leo Chapiro 24-Sep-15 8:04am    
No, my young friend, it gives a right one:

var square = 0;
var sum = 0;
var result = 0;

for (var i = 0; i < 11; i++){
square += Math.pow(i, 2);

sum += i;
}

result = Math.pow(sum, 2) - square;
console.log(result);

This gives 2640 !
Member 12008365 24-Sep-15 11:52am    
No, it doesn't give 2640 and if it did, it wouldn't be the right answer.

The output is 25164150, which is also the correct answer to the problem at projecteuler.net.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900