Click here to Skip to main content
15,918,193 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Have a int "n",I want to get a arrary in which every element is square of "index".The index is less than "n".Hope a optimal arithmetic...
Posted
Updated 20-May-14 19:48pm
v2

Since you mentioned "optimal arithmetic", if you prefer doing additions over multiplications, you can take advantage of the fact that the square number of n is equal to the sum of the first n odd numbers; therefore the difference between the consecutive squares (i*i) and (i+1)*(1+1) is equal to the (i+1)st odd number (2*i+1). You can reverse that dependency to construct the square numbers like this:
C++
void make_squares(int* square_array, int n) {
   int square = 0;                      // initialize square value
   int current_odd_number = 1;          // first odd number
   while (current_odd_number < n<<1) {  // last odd number will be 2*n-1, i. e. less than 2*n
      *square_array = square;           // assign current square value to current element
      square += current_odd_number;     // calc next square value
      current_odd_number += 2;          // calc next odd number
      ++square_array;                   // bump element pointer to next element
   }
}

Note that modern CPUs will likely be just as fast doing the multiplications as suggested in solution 1. Just wanted to point out an alternative.
 
Share this answer
 
v2
Comments
Nelek 21-May-14 5:15am    
Nice answer
[no name] 21-May-14 5:19am    
Great!
CPallini 21-May-14 5:32am    
5.
Sergey Alexandrovich Kryukov 21-May-14 11:19am    
My 5, but with one note: the CPUs will most certainly do this faster because the algorithm is applied for numbers. Your algorithm will just spend more time on that loop and other operations and makes no sense for numbers at all. However, it can be effectively used for any more complex objects for which multiplication is defined and you want to define integer powers: matrix, anything, where you can really dramatically reduce the number of redundant operations.
—SA
Stefan_Lang 22-May-14 5:39am    
Yeah I know. I learned programming at a time when the Bresenham Algorithm actually sped up the drawing of lines on a computer. Sometimes I wish fixing performance in programs were still as trivial as that ;-)
Try:
C++
for(i = 0; i < n; i++)
   MyArray[i] = i * i;
 
Share this answer
 
v2
Comments
_Asif_ 21-May-14 1:56am    
Have we started doing homework? :) Just kidding!
codeprojectddx 21-May-14 20:33pm    
no
Legor 21-May-14 3:28am    
1 Million! Congratulations!
Kornfeld Eliyahu Peter 21-May-14 5:16am    
I smell your sweat...

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