코딩하는 개굴이

[HackerRank] Extra Long Factorials (Kotlin) 본문

알고리즘/HackerRank

[HackerRank] Extra Long Factorials (Kotlin)

개굴이모자 2022. 7. 30. 15:45
반응형

큰 숫자의 팩토리얼도 계산할 수 있는지를 묻는 문제이자, BigInteger 를 사용하는 법에 대해 알려주는 문제이다.

 

int 형의 메모리 크기는 4byte 로 표현이 가능한 범위는 -2,147,483,648 ~ 2,147,483,647이고 long은 메모리 크기는 8byte로 표현할 수 있는 범위는 -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807이다. 해당 범위가 넘어가는 경우가 존재한다면 오작동의 가능성이 존재한다.

 

따라서, 알고리즘을 풀 때, 무한의 정수가 들어가거나 큰 숫자가 들어갈 가능성이 있는 경우는 BigInteger를 사용하는 것을 권장한다.

본래 JAVA 에서는 BigInteger 가 문자열의 형태로 이루어져있어 어떠한 숫자든 담을 수 있는데, BigInteger 는 java.math 안에 있으며, 생성 시에, `BigInteger bigNumber = new BigInteger("100000000"); ` 이렇게 인자를 넘겨 선언한다.

 

Kotlin 의 경우 간단히 ~.toBigInteger, BigInteger.ONE 등을 사용해서 쉽게 풀 수 있는데, 아래와 같은 풀이를 참고해보자.

 

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 kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*

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

fun extraLongFactorials(n: Int): Unit {
    var factorials: BigInteger = BigInteger.ONE
    for (i in 1..n) {
        factorials *= i.toBigInteger()
    }
    System.out.println(factorials)
}

fun main(args: Array<String>) {
    val n = readLine()!!.trim().toInt()

    extraLongFactorials(n)
}
반응형

'알고리즘 > HackerRank' 카테고리의 다른 글

[HackerRank] Compare Triplets (Kotlin)  (0) 2022.07.09
[HackerRank] Super Reduced String (Kotlin)  (0) 2022.07.09
Comments