使用移位计算平方
原文鏈接: 使用移位計算平方
上一篇: atom Windows10 安裝 配置c++環境
下一篇: 二分查找
重復使用加法的復雜度是O(n)。我們使用位運算符可以在O(Logn)的時間內完成。
一個數的平方可以轉化為 如下的遞歸格式
square(6) = 4*square(3)square(3) = 4*(square(1)) + 4*1 + 1 = 9square(7) = 4*square(3) + 4*3 + 1 = 4*9 + 4*3 + 1 = 49 如果n是偶數,可以寫作:n = 2*x n2 = (2*x)2 = 4*x2 如果n是奇數,可以寫作:n = 2*x + 1n2 = (2*x + 1)2 = 4*x2 + 4*x + 1 floor(n/2) 可以通過右移運算實現. 2*x and 4*x 可以通過左移運算實現。
c++
#include <cstdio> #include <cstring> #include <iostream> #include <string>using namespace std;// 返回 n^2 int square(int n){if (n < 0)n = -n;if (n == 0)return 0;int x = n >> 1;return (n & 1) ?( (square(x) << 2) + (x << 2) + 1) : //奇數(square(x) << 2);//偶數} int main(){for (int i = -10; i < 10; i++){printf("%4d %4d\n", i, square(i) );}return 0; }
總結
- 上一篇: java多进程端口复用_多个程序监听同一
- 下一篇: 颜色叠加算法