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?
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;
}
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.
#include <iostream>
usingnamespace 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 );
}