Java implements the calculation of n factorial

1. Problem description

      The product of n numbers from 1 to n is called the factorial of n, denoted as n!. The requirement is to design an algorithm that can calculate its corresponding factorial from an input number.

2. Problem analysis

      This is a relatively simple problem. The so-called factorial is actually the operation of continuous multiplication of numbers within n. I think everyone has done the continuous addition problem, and the solutions of the two are actually very similar. But to understand the idea of ​​recursion will be more concise.

3. Solutions

  • plan 1:

      Since factorial is a continuous product, we can design a loop body and declare two variables outside the loop, one to store the product, the other to store the number temp to be calculated, and the product operation is performed in the loop body, and temp is self-added for each multiplication. And compare it with n, and so on, until temp>n ends the loop and return the result.

  • Scenario 2:

     As shown in the figure below, each operation needs to call the result of the previous one, that is, hand over the previous part of the task I did to others, and directly use the results of others when I need to do it. Moreover, the calculation of the factorial has an obvious end sign, that is, the task is completed after the n factorial is calculated. This is obviously a typical recursive problem, then the recursive idea is directly used for calculation.


4. Algorithm implementation

public class Box{	
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		while(true){
			System.out.print("please input a number:");
			int num = sc.nextInt ( ) ;
			System.out.println();
			System.out.println("method1---the factorial of "+num+" is:" +fact(num));
			System.out.println("method2---the factorial of "+num+" is:" +recurrence(num));
		}
		
	}
	//use loop multiplication
	public static int fact(int num){
		int temp=1;
		int factorial=1;
		while(num>=temp){
			factorial=factorial*temp;
			temp++;
		}
		return factorial;
	}
	// use recursion
	public static int recurrence(int num){
		if(num<=1)
			return 1;
		else
			return num*recurrence(num-1);
	}
}

operation result



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944796&siteId=291194637