重写x的n次方函数
来源:互联网 发布:哨兵向导耽美小说知乎 编辑:程序博客网 时间:2024/04/28 15:57
环境:vs2010,C++
三种不同的方式,power1为直接相乘n次;power2为递归实现;PowerFun模仿STL中pow库函数实现,效率比较高。
#include <iostream>#include <time.h>//#include <algorithm>using namespace std;int PowerFun(int x, unsigned int n){int result = 1;if(n != 0){while ((n & 1) == 0){n >>= 1;x *= x;}result = x;n >>= 1;while (n != 0){x *= x;if((n & 1) != 0)result *= x;n >>= 1;}}return result;}int power1(int x, unsigned int n) { int result = 1; while (n--) result *= x; return result; } int power2(int x, unsigned int n) { if (n == 0) return 1; else if (n == 1) return x; else { if (n % 2 == 1) return power2(x, n / 2) * power2(x, n / 2) * x; else return power2(x, n / 2) * power2(x, n / 2); } } int main(){int nFloor = 2;int count = 30;clock_t clock_begin, clock_end;clock_begin = clock();for (int i = 0; i < count; i++)printf("%d的%d次方为 %d \n", nFloor, i, PowerFun(nFloor, i));clock_end = clock();printf("共耗时%d毫秒\n", clock_end - clock_begin);clock_begin = clock();for (int i = 0; i < count; i++)printf("%d的%d次方为 %d \n", nFloor, i, power1(nFloor, i));clock_end = clock();printf("共耗时%d毫秒\n", clock_end - clock_begin);clock_begin = clock();for (int i = 0; i < count; i++)printf("%d的%d次方为 %d \n", nFloor, i, power2(nFloor, i));clock_end = clock();printf("共耗时%d毫秒\n", clock_end - clock_begin);system("pause");return 0;}
- 重写x的n次方函数
- 编写函数求x的n次方
- x的n次方
- x的n次方
- X的n次方
- Pow(x,n) x的n次方
- 编写一个求x的n次方的函数
- 计算x的n次方
- 求X的N次方
- 求x的n次方
- 计算x的n次方
- 二分算法实现幂函数x的n次方 Pow(x, n)
- LeetCode 50. Pow(x, n) x的n的次方
- c++ 求x的n次方
- 递归计算x的N次方
- java 计算x的n次方
- java中输入X的N次方
- x的n次方求解 与 优化
- 3种工厂模式的比较 .
- viewDidLoad,viewWillDisappear, viewWillAppear区别
- u-boot:从NOR FLASH启动并支持NAND FLASH读写的移植
- MFC中SDI程序创建流程的回顾
- 一步步构建大型网站架构(非常不错!)
- 重写x的n次方函数
- CSS如何修改tr边框属性
- 对刷百度权重的见解
- 如何成为一个架构师
- Visual C++ 2005中使用 GNU Scientific Library
- 如何刷百度权重
- 创业者要会管理VC:投资你的VC离职了怎么办?
- 工厂模式
- isinstance(),getattr(), issubclass()