当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
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
边栏推荐
- 倒计时1天~2022云容灾产品线上发布会即将开始
- 如何轻松做好一个项目
- RecyclerView细节研究-RecyclerView点击错位问题的探讨与修复
- 帆软中单元格中隔行变色以及数量大于100字体变大变红设置
- 使用DialogFragment的一些感受及防踩坑经验(getActivity、getDialog为空,cancelable无效等)
- MySQL数据库讲解(九)
- 返回数组排序后下标
- Installation and use of postman pit
- ActiveMQ Basics
- VMware 15pro mounts the hard disk of the real computer in the deepin system
猜你喜欢
Some good articles on pthread multithreading
帆软实现分页时第一行和最后两行冻结方式
微信小程序客服接入,实现发送和接收消息
某政务云项目业务系统迁移调研实践
RecyclerView细节研究-RecyclerView点击错位问题的探讨与修复
logback-logger和root
Idea控制台乱码解决
VMware installation 64 bit XP Chinese tutorial
帆软中需要设置合计值为0时,一整行都不显示的解决办法
Wechat applet initializes Bluetooth, searches nearby Bluetooth devices and connects designated Bluetooth (I)
随机推荐
Some experience of using dialogfragment and anti stepping pit experience (getactivity and getdialog are empty, cancelable is invalid, etc.)
Promtail + Loki + Grafana 日志监控系统搭建
PySide2
How QT designer adds resource files
Detailed tutorial on the use of setinterval timing function of wechat applet
dp-能量项链
Visio installation error 1:1935 2: {XXXXXXXX
Three point positioning based on ibeacons (wechat applet)
Wechat applet obtains login user information, openid and access_ token
JDBC详解
ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory
redis数据库讲解(四)主从复制、哨兵、Cluster群集
Jira截取全图
Easyexcel读取excel表地理位置数据,按中文拼音排序
Wechat applet communicates with low-power Bluetooth - receives data sent by hardware (IV)
金融行业云迁移实践 平安金融云整合HyperMotion云迁移解决方案,为金融行业客户提供迁移服务
贷款市场报价利率(LPR)与贷款基准利率介绍
帆软中根据分类进行汇总
使用itextpdf实现截取pdf文档第几页到第几页,进行分片
多云数据流转?云上容灾?年前最后的价值内容分享