Complete N! The programming: 1, prepared by cycle algorithm; 2, prepared using a recursive algorithm;

Complete N! The programming

1, written in round-robin algorithm

#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, written in a recursive algorithm

#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; 
}

Although these two methods can be used, but recursion is too resource-intensive, and the cycle is a better choice

And if the recursive algorithm to solve the problem, if translate into a recursive loop, we should try to do so

Guess you like

Origin www.cnblogs.com/zgh666/p/11463181.html