算法之递归系列一

题目:

1、计算 (分治法)

问题描述

对于给定的n,要求在O(n)步内计算出 ,同时分析该程序的时间复杂性和空间复杂性。

 

 

输入:要计算的n,

输出:

思想:

1.  用普通算法实现计算量为 数量级;

2.  用分治法实现算法为O(n)级的

分治法具体实现:

利用函数:

F(n)=

 

 

 

程序

 

 

 

 

 

 

//*************************************************************************************
//对于给定的n,要求在O(n)步内计算出2的2的n次幂 ,同时分析该程序的时间复杂性和空间复杂性。
//利用分治法解题
//author:dongkaiying
//use the common method ,we can find that if we use 'double ',the 'n' can only be the
//region lower than 9; so we must find a better method to reduce the complexity of the
//method.We use the "fenzhifa" we called.
//*************************************************************************************
#include<iostream.h>
#include<stdio.h>
double common_M(int n);
double FenZhi_M(int n);
void main()
{
 cout<<"Please enter the 'n' you need:"<<endl;
 int n;
 cin>>n;
 //use the easiest method to compute the value;
    double j=common_M(n);
 cout<<"Use the common method to compute the value is:"<<j<<endl;
 double m=FenZhi_M(n);
 cout<<"Use another common method to compute the value is:"<<m<<endl;
 return;
}
//this method's complexity .:2's n cimi
double common_M(int n)
{
 double result=1;
 double result_1=1;
 for(int x=1;x<=n;x++)
 {
  result*=2;
 }
 for(x=1;x<=result;x++)
 {
  result_1*=2;
 }
 return result_1;
}


//use the digui method;
double  FenZhi_M(int n)
{
 if(n==1)
  return 4;
 else
  return  FenZhi_M(n-1)*FenZhi_M(n-1);
 
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值