基本算法思想(三)

递归算法

1.什么是递归

递归简单来说就是在运行过程中不断调用自己,直到碰到终止条件,返回结果的过程。

递归可以看作两个过程,分别是递和归。递就是原问题把要计算的结果传给子问题;归则是子问题求出结果后,把结果层层返回原问题的过程。

下面设一个需要经过三次递归的问题,为大家详细看一下递归的过程:

当然,现实中我们遇到递归问题是不会按照图中一样一步一步想下来,主要还是要掌握递归的思想,找到每个问题中的规律。

2.什么时候使用递归

 递归算法无外乎就是以下三点:
(1)大问题可以拆分为若干小问题

(2)原问题与子问题除数据规模不同,求解思路完全相同

(3)存在递归终止条件

3.递归的实际运用(阶层计算)

 求N的阶层。

首先按照思路分析是否可以使用递归算法:

(1)N!可以拆分为(N-1)!*N

(2)(N-1)!与N!只有数字规模不同,求解思路相同

(3)当N=1时,结果为1,递归终止

4.C语言实现

#include <stdio.h>
#include <stdlib.h>

long fact(int n); //函数声明

void main()
{
     int i;

     printf("请输入要计算阶乘的一个整数:");
     scanf("%d",&i);
     printf("%d的阶乘结果为:%ld\n",i,fact(i));
}

long fact(int n)
{
    if(n<=1)
        return 1;
    else
        return n*fact(n-1);
}

 5.C++语言实现

 5.1for循环

#include<bits/stdc++.h>
using namespace std;
inline void read(int &a){
	a=0; char c;
	while((c=getchar())<48);
	do a=a*10+(c^48);
	while((c=getchar())>47);
}
inline void write(int x) {
	if(x<0) {
		x=-x;
		putchar('-');
	}
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int main()
{
 int n,m;
 read(n);
 int t=1;
 if(t<1){
 	write(1);
 }
 else{
 	for(int i=1;i<n+1;i++){
 		t*=i;
	 }
	 write(t);
 }
 return 0;
 }

 5.2while循环

#include<bits/stdc++.h>
using namespace std;
inline void read(int &a){
	a=0; char c;
	while((c=getchar())<48);
	do a=a*10+(c^48);
	while((c=getchar())>47);
}
inline void write(int x) {
	if(x<0) {
		x=-x;
		putchar('-');
	}
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int main()
{
 int n,m;
 read(n);
 int t=1;
 if(t<1){
 	write(1);
 }
 else{
 	int f=1;
 	while(f<=n){
 		t*=f;
 		f++;
	 }
	 write(t);
 }
 return 0;
 }

 5.3递归法

#include<bits/stdc++.h>
using namespace std;
inline void read(int &a){
	a=0; char c;
	while((c=getchar())<48);
	do a=a*10+(c^48);
	while((c=getchar())>47);
}
inline void write(int x) {
	if(x<0) {
		x=-x;
		putchar('-');
	}
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int main()
{
 int n,m;
 read(n);
 int t=1;
 if(t<1){
 	write(1);
 }
 else{
 	int f=1;
 	while(f<=n){
 		t*=f;
 		f++;
	 }
	 write(t);
 }
 return 0;
 }

 6.Java语言实现

6.1使用循环的方式

//求n的阶乘
public class Demo3 {
 
    public static void main(String[] args) {
//        方法一:
        System.out.println("="+factorial(5));
 
    }
 
//    循环
    public static int factorial(int n) {
//        用于记录阶乘结果,必须为1,乘积不变
        int result = 1;
//        循环n次相乘
        for (int i = 1; i <= n; i++) {
            result *= i;
            System.out.print(i+"*");
        }
//        返回结果
        return result;
 
    };
 
}

6.2使用递归的方式

//求n的阶乘
public class Demo3 {
 
    public static void main(String[] args) {
 
//        方法二:
       for (int i = -3; i<=30; i++){
           System.out.println("变量为"+i+":"+factorial2(i));
       }
    }
 
 
 
//    递归
    public static int factorial2(int n){
//        递归的回归条件
        if(n==1){
            return 1;
        }
 
        //有效数据校验
        if(n==0){
           return 0;
        }
        if(n<0){
            return -1;
        }
 
        return n*factorial2(n-1);
    }
}

7.Python语言实现

7.1普通的for循环语句来计算阶乘 

 #函数实现
 def factorial(num):
    a=1
    #for循环遍历
    for i in range(1,num+1):
         a*=i
    return a

 n = int(input())
 print(factorial(n))

 7.2while循环语句来计算阶乘

#输入n的值
n=int(input())            
ans=n
i=1
if n ==0:
    print(1)
else:
	#while循环
    while i <n:                                              
        ans=ans*i                                            
        i=i+1                                               
    print(ans)        
 

 7.3使用递归函数

(1)写法一

#函数实现
def factorial(n):
    if n==0:
        return 1
    else:
        #递归调用
        return factorial(n-1)*n
    
n = int(input())
print(factorial(n))

 (2)写法二

#函数实现
def factorial(n):
      #三元运算表达式
      return 1 if n < 2 else n * factorial(n - 1)
 
#输入n的值
n = int(input())
print(factorial(n))

7.4借助functools中的reduce模块

(1)写法一

#导入functools
import functools
#输入n的值
n = int(input())
#lambda函数+reduce模块
result = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(n)
print(result)

 【 注:Lambda是一种不需要名字(即标识符)、由一个单独表达式成的匿名内联函数,表达式会在调用时被求值。
创建 lambda 函数的语法为:lambda [parameters]: expression 】

(2)写法二

#从functools中导入reduce
from functools import reduce
#函数实现
def factorial(num):
    return reduce(lambda x,y:x*y,range(1,num+1))

#输入n的值
n = int(input())
print(factorial(n))

7.5借助math库,使用math库的factorial方法

#导入math模块
import math
#函数实现
def fact(num):
	#借助math模块中的factorial方法
    return math.factorial(num)

#输入n的值
n = int(input())
print(fact(n))

 【注:Python math.factorial(x) 方法返回 x 的阶乘。】

7.6使用eval适配表达式

#函数实现
def fact(num):
	#eval适配表达式实现
	return eval('*'.join(map(str,range(1,num+1))))

#输入n的值
n = int(input())
print(fact(n))

 【注:eval() 函数用来执行一个字符串表达式,并返回表达式的值。
eval() 方法的语法:eval(expression[, globals[, locals]]) 】

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值