the algorithms to solve the question X^N
来源:互联网 发布:q房网经纪人端口下载 编辑:程序博客网 时间:2024/06/06 02:48
Algorithm 1:time complexity O(N)
double pow(double x, long n){ if(n==0) return 1; /*when n=0 whatever the x is,the pow is 1*/ if(n==1) return x; /*when n=1 the result is x itself*/ else { double tempa=1.0000; while(n--) tempa=tempa*x; return (tempa); /*every time make n-- then multiply a xto get the result*/ }}Algorithm 2:time complexity O(log(N))
double pow(double x, long n){ if(n==0)return 1; /*when n=0 whatever the x is,the pow is 1*/ if(n==1) return x; /*when n=1 the result is x itself*/ double temp=1.0; while(n) {if(n%2) temp*=x; /*when n is odd*/x*=x;n/=2; } return temp;}Algorithm 3:time complexity O(log(N))
double pow(double x, long n){ if(n==0) return 1; /*when n=0 whatever the x is,the pow is 1*/ if(n==1) return x; /*when n=1 the result is x itself*/ if(n%2==0) return pow(x*x,n/2); /*when n is an even increase x to x*x and decrease n to n/2*/ else return pow(x*x,n/2)*x; /*when n is an odd increase x to x*x and decrease n to n/2 an then multiply x*/}
Actually,algorithm 2 is a iterative version of algorithm 3,while algorithm is a recursive version.
- the algorithms to solve the question X^N
- The answer to the question
- The Clojure Program To solve N Queens Problem
- The Question
- how to solve the problem we met?
- How to solve the Candy problem?
- SOLUTION TO SOLVE THE ORACLE QEQUENCE
- To be or Not to be that is the question
- ISTQB question pattern and tips to solve
- How to solve the "undefined reference to '__sync_sub_and_fetch_4'" compilation problem
- How to solve the "undefined reference to '__sync_sub_and_fetch_4'" compilation problem
- Algorithms Part 1-Question 1- the number of inversions-逆序数计算算法
- Algorithms Part 1-Question 3- the min cut problem-最小割问题
- The FOUR_QUEEN question solutions
- 640. Solve the Equation
- 640. Solve the Equation
- Solve the Equation
- How To Solve The Problem : Unstable Ubuntu ADSL Connection
- 张飞流水账:超级搞笑诠释人生哲理
- 2013.3.28 第一次面试总结
- 堆排序
- HDU 2601 An easy problem
- CFileDialog 使用 OFN_ALLOWMULTISELECT 标志选择多个文件
- the algorithms to solve the question X^N
- 谷歌地图
- 高速发展的中国的社会问题,潜在超级大国和未来经济大势
- USACO报告:chapter1.1:Your Ride Is Here
- C++ 学习使用 MFC CFileDialog
- powershell basic
- powershell connect sql server
- powershell seach const variable
- 通过反射获得类的实例对象