Contents

Factorial (with.Java)

   Feb 13, 2024     2 min read

This is an article about the “factorial” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

ifactorial (i!) means the product of integers from 1 to i. For example 5! = 5 _ 4 _ 3 _ 2 _ 1 = 120. Given an integer n, complete the solution function to return the largest integer i that satisfies the following conditions.

-i! ≤ n

Restrictions

  • 0 < n ≤ 3,628,800

Input/Output Example

nresult
362880010
73

My solution to the problem

class Solution {
     public int solution(int n) {
         int answer = 0;
         int temp = 1;
         for(int i = 2; i <= 10; i++){
             for(int j = i; j >= 2; j--){
                 temp *= j;
             }
             if(temp == n){
                 answer = i;
                 return answer;
             } else if(temp > n){
                 answer = i - 1;
                 return answer;
             } else {
                 temp = 1;
             }
         }
         return answer;
     }
}

Solution explanation

solution(int n): Returns the minimum number of numbers that can represent the given integer n as a factorial.

Use the for statement to calculate the factorial for numbers from 2 to 10.

Calculate the factorial from the current number to 2 through the inner for statement and store it in temp.

If the calculated factorial matches n, that number is returned as the result.

If the factorial is greater than n, the previous number is the minimum number and is returned as the result.

Code Advantages

  • Simple implementation: The implementation required to solve the problem is simple.
  • Intuitive logic: It has intuitive logic by sequentially checking given conditions.

Code Disadvantages

  • Applicable only to a specific range: Currently, the factorial is calculated only for numbers from 2 to 10, so if it is outside this range, accurate results cannot be obtained.