如何获得这样的数组? [英] How to get a array like this?

查看:68
本文介绍了如何获得这样的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个intn,我想得到一个arrary,其中每个元素都是index的平方。索引小于n。希望最佳算术...

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...

推荐答案

由于你提到了最优算术,如果你更喜欢在乘法上做加法,你可以利用n的平方数等于前n个奇数之和的事实。 ;因此,连续方块(i * i)和(i + 1)*(1 + 1)之间的差等于第(i + 1)st个奇数(2 * i + 1)。您可以反转该依赖关系以构建如下的平方数:

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:
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
   }
}



请注意,现代CPU可能与解决方案1中建议的乘法一样快。只是想指出一个替代方案。


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.


尝试:

Try:
for(i = 0; i < n; i++)
   MyArray[i] = i * i;


这篇关于如何获得这样的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆