当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
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云容灾产品线上发布会即将开始
- 报表FCRA考试题集及答案(错了11题)
- JDBC和servlet写CRUD的接口总结
- logback-logger和root
- MySQL数据库讲解(九)
- Essential difference between restful WebService and gSOAP webservice
- dp-能量项链
- postman批量生产body信息(实现批量修改数据)
- VMware 15pro mounts the hard disk of the real computer in the deepin system
- 帆软中单元格中隔行变色以及数量大于100字体变大变红设置
猜你喜欢
随机推荐
Easyexcel读取excel表地理位置数据,按中文拼音排序
帆软实现一个单选按钮,可以统一设置其他单选按钮的选择状态
服务器日志分析工具(识别,提取,合并,统计异常信息)
win10自带Groove音乐不能播放CUE和APE文件的一种曲线救国办法,自己创建aimppack插件包,AIMP安装DSP插件
MySQL数据库讲解(七)
微信小程序客服接入,实现发送和接收消息
第四届“传智杯”全国大学生IT技能大赛(决赛B组) 题解
On the problem of cliff growth of loss function in the process of training
线程间控制之CountDownLatch和CyclicBarrier使用介绍
预览CSV文件
连接公司跳板机取别名
VMware 15pro mounts the hard disk of the real computer in the deepin system
如何快速批量创建文本文档?
Wechat applet communicates with low-power Bluetooth - sending data to hardware (III)
Switch usage (wechat applet)
Wechat applet communicates with low-power Bluetooth - receives data sent by hardware (IV)
Subscription number development of wechat applet (message push)
Jmeter安装教程以及我遇到的问题的解决办法
MySQL-InnoDB-事务
Visio installation error 1:1935 2: {XXXXXXXX