[Blue Bridge Cup Exercises] High-precision factorial calculation (based on java)

resource constraints

Time limit: 1.0s Memory limit: 512.0MB

Problem Description

Input a positive integer n and output the value of n!.
where n!=1 2 3*...*n.

Algorithm Description

n! may be very large, and the range of integers that can be represented by a computer is limited, so a high-precision calculation method is required. Use an array A to represent a large integer a, A[0] represents the ones digit of a, A[1] represents the tens digit of a, and so on.
Multiplying a by an integer k becomes multiplying each element of the array A by k, please pay attention to the corresponding carry.
First set a to 1, then multiply by 2, multiply by 3, when it is multiplied to n, the value of n! is obtained.

import java.util.*;

public class HighPrecisionFactorial
{
    
    
	public static void main(String[] args) throws IndexOutOfBoundsException
	{
    
    
		Scanner sr = new Scanner(System.in);
		int n = sr.nextInt();
		sr.close();
		ArrayList<Integer> list = new ArrayList<>();
		// 这里使用 ArrayList效率比 LinkedList高
		// 对于 get和 set操作,ArrayList效率高(基于动态数组实现)
		// 对于 add和 remove 操作,linkedList效率高(基于链表实现)
		// 若在这里使用 LinkedList程序会超时
		list.add(1);
		int k = 0;
		// 进位
		for(int i = 2;i <= n;i++)
		{
    
    
			// 阶乘从 2开始
			for(int j = 0;j < list.size();j++)
			{
    
    
				int temp = list.get(j) * i;
				if((temp + k) >= 10)
				{
    
    
					list.set(j, (temp + k) % 10);
					k = (temp + k) / 10;
					try
					{
    
    
						list.get(j + 1);
					}
					catch(IndexOutOfBoundsException exception)
					{
    
    
						list.add(0);
						// 数组扩容
					}
				}
				else
				{
    
    
					list.set(j, temp + k);
					k = 0;
				}
			}
		}
		
		for(int index = list.size() - 1;index >= 0;index--)
		{
    
    
			System.out.print(list.get(index));
		}
	}
	
}

Guess you like

Origin blog.csdn.net/x5445687d/article/details/123032139