完成N!的程序编写: 1、用循环算法编写; 2、用递归算法编写;

完成N!的程序编写

1、用循环算法编写

#include<iostream>
using namespace std;

int main(){
    int n;
    long result = 1;
    cin>>n;
    for(int i = 2; i <= n; i++){
        result *= i;
    }
    cout<<result;
    return 0; 
}

2、用递归算法编写

#include<iostream>
using namespace std;

long f(int n){
    if(n == 1){
        return 1;
    }
    return f(n-1)*n;
} 

int main(){
    int n;
    cin>>n;
    cout<<f(n);
    return 0; 
}

这两种方法虽然都可以用,但是递归太耗费资源了,循环是更好的选择

而且如果用递归算法解决问题时,如果递归能转化为循环,要尽量这么去做

猜你喜欢

转载自www.cnblogs.com/zgh666/p/11463181.html