Four Methods of C ++ factorial

Source: Internet
Author: User

To sum up the methods used to calculate the factorial.

Preface: ① each code only provides the idea of factorial, so that it can be encoded as needed. The code is not robust! ② Each program is tested correctly within 1 to 10.

 

Code 1:

# Include <iostream> using namespace STD; int FAC (INT); int main () {int N; while (CIN> N) {cout <n <"! = "<FAC (n) <Endl;} return 0;} int FAC (int x) {register int I, F = 1; // define the register variable for (I = 1; I <= x; I ++) f * = I; return F ;}

Analysis: This program calls FAC () every time it inputs n to obtain the result of brute force computation.

 

Code 2:

#include<iostream>using namespace std;int a[11];void init();int main(){init();int n;while(cin>>n){cout<<n<<"!= "<<a[n]<<endl;}return 0;}void init(){int i;a[0]=1;for(i=1;i<=10;i++)a[i]=i*a[i-1];}

Analysis: This program uses the array to record the obtained results, and uses the obtained results when calculating the next result.

 

Code 3:

# Include <iostream> using namespace STD; int FAC (INT); int main () {int I; for (I = 1; I <= 10; I ++) {cout <I <"! = "<FAC (I) <Endl;} return 0;} int FAC (INT X) {static int F = 1; // static local variable F * = X; return F ;}

Analysis: it should be said that the code is the least practical, mainly to learn static local variables.

 

Code 4:

# Include <iostream> using namespace STD; int FAC (INT); int main () {int N; while (CIN> N) {cout <n <"! = "<FAC (n) <Endl;} return 0;} int FAC (int x) // recursive function {int F; if (x = 0 | x = 1) F = 1; elsef = FAC (x-1) * X; return F ;}

Analysis: We always think that recursive technology is amazing. Although not ideal in terms of time and space, it does allow us to use fuzzy programming. You do not have to parse every detail.

 

Written at the end: the program is a magical thing. Programming is a very important capability.

Welcome!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.