当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
2022-04-23 14:09:00 【白马非马·】
题目:x的n次方,结果输出
package demo4_8;
public class leijia {
static int temp;
public static void main(String[] args) {
//一道题目思考递归的时间复杂度
//问题:x的n次方
int x=2;
int n=8;
System.out.println("方法一:"+method1(x,n));
System.out.println("方法二:"+method2(x,n));
System.out.println("方法三:"+method3(x,n));
System.out.println("方法四:"+method4(x,n));
}
//方法一:直接求解(时间复杂度为O(n)
public static int method1(int x,int n){
int result=1;
for(int i=0;i<n;i++){
result*=x;
}
return result;
}
//方法二:递归的方法:时间复杂度还是O(n)
public static int method2(int x,int n){
if(n==0) return 1;
return method2(x,n-1)*x;
}
//方法三:递归的方法:时间复杂度还是O(n)
//通过满二叉树进行计算,时间复杂度还是O(n)
public static int method3(int x,int n){
if(n==0) return 1;
if(n%2==1) return method3(x,n/2)*method3(x,n/2)*x;
return method3(x,n/2)*method3(x,n/2);
}
//方法四:递归的方法:时间复杂度还是O(n)
public static int method4(int x,int n){
if(n==0) return 1;
temp=method4(x,n/2); //记录中间变量
System.out.println("次数");
if(n%2==1) return temp*temp*x;
return temp*temp;
}
}
版权声明
本文为[白马非马·]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42974034/article/details/124055567
边栏推荐
- DP energy Necklace
- On the multi-level certificate based on OpenSSL, the issuance and management of multi-level Ca, and two-way authentication
- dp-能量项链
- Algorithem_ReverseLinkedList
- VMWare安装64位XP中文教程
- mysql锁数据库锁
- findstr不是内部或外部命令解决方法
- 教育行业云迁移最佳实践:海云捷迅使用HyperMotion云迁移产品为北京某大学实施渐进式迁移,成功率100%
- HyperBDR云容灾V3.3.0版本发布|容灾功能升级,资源组管理功能优化
- Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
猜你喜欢

微信小程序客服接入,实现发送和接收消息

Storage path of mod subscribed by starbound Creative Workshop at Star boundary

01-NIO基础之ByteBuffer和FileChannel

Logback logger and root

星界边境Starbound创意工坊订阅的mod的存放路径

正则表达式

政务云迁移实践 北明数科使用HyperMotion云迁移产品为某政府单位实施上云迁移项目,15天内完成近百套主机迁移

線程組ThreadGroup使用介紹+自定義線程工廠類實現ThreadFactory接口

Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动

krpano全景之vtour文件夹和tour
随机推荐
线程间控制之CountDownLatch和CyclicBarrier使用介绍
Logback logger and root
sql中出现一个变态问题
MySQL-InnoDB-事务
星界边境文本自动翻译机(高级版)使用说明
logback-logger和root
Recyclerview advanced use (II) - simple implementation of vertical drag and drop sorting
Oracle-数据泵使用
Three point positioning based on ibeacons (wechat applet)
Operation instructions of star boundary automatic text translator (advanced version)
Wechat applet input hidden and inoperable settings
困扰多年的系统调研问题有自动化采集工具了,还是开源免费的
gzip和gunzip 解压参数详解
Understand the concepts of virtual base class, virtual function and pure virtual function (turn)
JDBC详解
ActiveMq基础知识
使用DialogFragment的一些感受及防踩坑经验(getActivity、getDialog为空,cancelable无效等)
Storage path of mod subscribed by starbound Creative Workshop at Star boundary
帆软中根据分类进行汇总
01-NIO基础之ByteBuffer和FileChannel