Calculate square of number with sum of odd numbers

Hello,
I want to Calculate the square of the number with sum of odd numbers.
For example,
n = 5 and square of it is 25. I want to calculate it with sum of off numbers 1 + 3 + 5 + 7 + 9 = 25 instead using power.
I wrote a program but I think this isn't a good solution and while pow(n,2) isn't good condition.
Do you have another algorithm?

n = 5, 5^2 = 25, 1 + 3 + 5 + 7 + 9 = 25

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <iostream>
using namespace std;

int main()
{
	int n, sum = 0 ;
	cin >> n;
	int i = 1;
	while (pow(n,2) != sum)
	{
		sum += i;
		i += 2;
	}
	for (int j = 1; j <=i ; j+=2)
	{
		cout << j << " ";
	}

	return 0;

}
result = n*n;
while(result != sum) //but, the compiler should have done this for you, if it was able to determine that N never changes... 'should' but 'did it'...

the 'better algorithm' would be if you can figure out where to stop.
how do you know to stop at 5 for 3*3? How do you know to stop at 9 for 5*5? Is there a pattern to this? ... if there is, you are home free. Also, the for loop is pointless. You can get your output in the while loop -- the for loop just doubles your work done.

what about...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

int main()
{
	int n, sum = 0 ;	
	int i = 1;
	
	n = 11;
	for(int j = 0; j < n; j++) //this is the key.  but is it *always* right or 
                                            //just right for a few test cases...		
	{		
		//cout << i << endl;
		sum += i;
		i+=2;		
	}		
	cout << sum << endl;
}
Last edited on
@jonnin, the sum of the first N odd numbers is N^2.

You could ask @Adam2016 to practice proof by induction on it (though it's easier as an arithmetic series).
Hehe. I suspected it was true but I have sworn off doing proofs esp for someone else's homework.

the above is overly explicit. you should be able to roll that on down to just a single variable loop with just a single += statement if you want to performance tune it or something. Its easier to understand with the simple code above.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int squared( int N )
{
    int sum = 0;
    for ( int odd = 1; N--; odd += 2 ) sum += odd;
    return sum;
}

int main()
{
   int N;
   cout << "Enter N (>=0): ";   cin >> N;
   cout << N << " squared is " << squared( N );
}
Last edited on
@jonnin

1
2
3
4
5
6
7
8
9
10
11
Prove: (i = 0)S(n) 2n + 1 = (n + 1)^2 [this is the theorem to be proven but starts with 0 so that the first odd number is 1 as we would like]

case n = 0 [verifying 1]: 2(0) + 1 = 1 = (0 + 1)^2

general case:
if (i = 0)S(n) 2n + 1 = (n + 1)^2 then (i = 0)S(n + 1) 2n + 1 = ((n + 1) + 1)^2 = (n + 2)^2
let (i = 0)S(n) 2n + 1 = (n + 1)^2
(i = 0)S(n + 1) 2n + 1 = (n + 1)^2 + 2(n + 1) + 1
= n^2 + 2n + 1 + 2n + 2 + 1
= n^2 + 4n + 4
= (n + 2)^2 Q.E.D.


I hope that's right; otherwise my name will be a farce.
Topic archived. No new replies allowed.