day16 1381 factorial (control range)

1381. Factorial

N N The factorial of N (denoted asN! N!N ! ) Means from1 to 11 toNNN (including1 11 andNNN ) the product of all integers.

The results of factorial operations are often very large.

Now, given the number NNN , please find outN! N!What is the non-zero number on the far right of N !

For example, 5! = 1 × 2 × 3 × 4 × 5 = 120 5! = 1×2×3×4×5=1205!=1×2×3×4×5=1 2 0 , so5! 5!5 ! The rightmost non-zero number is2 22

The input format is
one line and contains an integer NNN

Output format
Output an integer, which means N! N!N ! The rightmost non-zero number.

Data range
1 ≤ N ≤ 1000 1 ≤ N ≤ 10001N1 0 0 0
Input example:

7

Sample output:

4

Ideas:

120!The factorial of is far beyond the longrange, but we only need to get the last non-zero element, so we only need to do some control to control it within 1e9the range (a suitable range selected by ourselves).

There are two control methods:

  1. Remove the last one 0, that is, keep dividing 10, because the last non-zero bit has 0no effect on the answer.
  2. Regarding the modulus of the factorial result 1e9, because of the first operation, it is impossible to have consecutive ones 9in the subsequent 0, so we can take the modulus to control the range.

Java code


import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        long res = 1;
        for(int i = 1;i <= n;i++){
    
    
            res *= i;
            while(res % 10 == 0) res /= 10;
            res %= 1e9;
        }
        //经历了上面的while循环后,res的最后一位就是非0位
        System.out.println(res % 10);
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/113872236