View previous topic :: View next topic |
Author |
Message |
manc Grandmaster Cheater
Reputation: 1
Joined: 16 Jun 2006 Posts: 551
|
Posted: Sun Oct 02, 2011 11:36 pm Post subject: [C++] What is wrong with me |
|
|
I'm trying to do this.
Quote: |
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
|
Yet, my code keeps yielding an answer that is wrong somehow. Anyone see any immediate flaws?
Code: |
#include <iostream>
using namespace std;
int main(void)
{
int k = 0;
for(int i = 0; i<100; i++){
k = k + i;
}
int squareOfSum = k*k;
k = 0;
for(int i = 0; i<100; i++){
k = k + i*i;
}
int sumOfSquares = k;
cout << (squareOfSum - sumOfSquares);
return(0);
}
|
Thanks guise<3
_________________
|
|
Back to top |
|
 |
callmenuge Cheater
Reputation: 0
Joined: 12 Feb 2011 Posts: 42
|
Posted: Sun Oct 02, 2011 11:58 pm Post subject: |
|
|
I remember doing that problem. Here is my solution for that problem:
Code: | int main()
{
int s = 0, r = 0;
for(int z = 0; z <= 100; z++)
{
s += z * z;
r += z;
}
int sr = (r * r) - s;
printf("Answer: %i", sr);
return 0;
} |
I'm sorry for the poor naming convention. There's a reason for it but I won't get to that. The obvious difference is the operator in the conditional part of the for-loop. Mine is a less-than-or-equal-to whereas yours is a less-than.
I'm sure my code is not the optimal solution. Wiccan and Slovach--feel free to give me pointers where I can improve my coding practices and habits. Pun intended.
|
|
Back to top |
|
 |
manc Grandmaster Cheater
Reputation: 1
Joined: 16 Jun 2006 Posts: 551
|
Posted: Mon Oct 03, 2011 1:58 am Post subject: |
|
|
I can't believe i forgot those fuckers. I solved it..thanks..
_________________
|
|
Back to top |
|
 |
callmenuge Cheater
Reputation: 0
Joined: 12 Feb 2011 Posts: 42
|
Posted: Mon Oct 03, 2011 2:03 am Post subject: |
|
|
No problem, amigo. I'm glad I helped.
|
|
Back to top |
|
 |
|