当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
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
边栏推荐
- How QT designer adds resource files
- STD:: map and STD:: vector memory free
- HyperMotion云迁移完成阿里云专有云产品生态集成认证
- Can I compile the header file and source file of the template separately
- 帆软报表设置单元格填报以及根据值的大小进行排名方法
- 快速搞懂线程实现的三种方式
- Algorithem_ReverseLinkedList
- squid代理
- RecyclerView细节研究-RecyclerView点击错位问题的探讨与修复
- Idea控制台乱码解决
猜你喜欢

MySQL数据库讲解(八)

在MAC上安装mysql

About the configuration and use of json5 in nodejs

On the multi-level certificate based on OpenSSL, the issuance and management of multi-level Ca, and two-way authentication

win10自带Groove音乐不能播放CUE和APE文件的一种曲线救国办法,自己创建aimppack插件包,AIMP安装DSP插件

MySQL-InnoDB-事务

云迁移的六大场景

HyperBDR云容灾V3.2.1版本发布|支持更多云平台,新增监控告警功能

星界边境文本自动翻译机使用说明

使用itextpdf实现截取pdf文档第几页到第几页,进行分片
随机推荐
JSP学习2
文字组合,不重复,做搜索或查询关键字匹配
某政务云项目业务系统迁移调研实践
多云数据流转?云上容灾?年前最后的价值内容分享
帆软实现一个单选按钮,可以统一设置其他单选按钮的选择状态
线程间控制之CountDownLatch和CyclicBarrier使用介绍
Wechat applet communicates with low-power Bluetooth - receives data sent by hardware (IV)
mysql查询库大小
DP - [noip2000] grid access
Wechat applet communicates with low-power Bluetooth - sending data to hardware (III)
帆软调用动态传参的方法,在标题中设置参数
线程组ThreadGroup使用介绍+自定义线程工厂类实现ThreadFactory接口
Redis数据库讲解(一)
预览CSV文件
std::map 和 std::vector 内存释放
回顾2021:如何帮助客户扫清上云最后一公里的障碍?
DP energy Necklace
VMware Workstation 无法连接到虚拟机。系统找不到指定的文件
OpenStack如何跨版本升级
VMware 15pro mounts the hard disk of the real computer in the deepin system