알고리즘 단련장/해커랭크

[해커랭크] Extra Long Factorials

snapcoder 2025. 8. 14. 18:35
728x90
반응형
SMALL

[해커랭크] Extra Long Factorials

 

https://www.hackerrank.com/challenges/extra-long-factorials/problem?isFullScreen=true

 

Extra Long Factorials | HackerRank

Calculate a very large factorial that doesn't fit in the conventional numeric data types.

www.hackerrank.com

 

The factorial of the integer , written , is defined as:

 

Calculate and print the factorial of a given integer.

For example, if , we calculate  and get .

Function Description

Complete the extraLongFactorials function in the editor below. It should print the result and return.

extraLongFactorials has the following parameter(s):

  • n: an integer

Note: Factorials of  can't be stored even in a  long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers, but we need to write additional code in C/C++ to handle huge values.

We recommend solving this challenge using BigIntegers.

Input Format

Input consists of a single integer 

Constraints

 

Output Format

Print the factorial of .

Sample Input

 

Sample Output

 

Explanation

 

 

 

 

 

풀이

BigInteger를 사용하라고 친절히 문제에 적혀져있는 그대로 구현

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'extraLongFactorials' function below.
     *
     * The function accepts INTEGER n as parameter.
     */

    public static void extraLongFactorials(int n) throws IOException {
    // Write your code here
       
        BigInteger dap = BigInteger.ONE;
        for(long i=1; i<=n; i++){
            dap = dap.multiply(BigInteger.valueOf(i));
        }
       
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        bw.write((String.valueOf(dap)));
        bw.flush();
        bw.close();
        return;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        Result.extraLongFactorials(n);

        bufferedReader.close();
    }
}

 

 

728x90
반응형
LIST