CodingTest/백준(with Java)

백준 1271번문제

dongok218 2024. 10. 10. 16:57

[내가 작성한 정답]

package BaekJoon;
import java.util.Scanner;

public class baek1721 {
	public static void main (String args[]) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int m = scanner.nextInt();
		int quotient, remainder;
		quotient = n / m;
		remainder = n % m;

		System.out.println(quotient);
		System.out.println(remainder);
	}
}

 

[문제점]

1. 이 문제에서는 큰 정수, 즉 int형이나 long형의 범위를 초과하는 숫자가 입력으로 주어진다. 이 경우 BigInteger를 이용해야 한다.

 

[해결방법]

1. BigInteger형으로 n과 m을 우선 입력받고, BigInteger 클래스에 있는 divide함수와 reminder함수를 이용해서 n을 m으로 나눈 값과 나머지를 출력하면 된다.

 

[해결 답안]

package BaekJoon;
import java.math.BigInteger;
import java.util.Scanner;

public class baek1721 {
	public static void main (String args[]) {
		Scanner in = new Scanner(System.in);
		BigInteger n = in.nextBigInteger();
		BigInteger m = in.nextBigInteger();
		
		in.close();
		
		//n을 m으로 나눈다. divide는 BigInteger에 있는 함수ㄴ
		System.out.println(n.divide(m));
		System.out.println(n.remainder(m));
	}
}

◆ BigInteger를 사용해야 하는 이유

가끔 알고리즘 문제들을 풀다 보면 큰 수를 처리해야 할 때가 있는데, 여기서 큰 수란 int형, long형의 범위를 넘어설 때이다. int형이나 long형의 범위를 넘어서게 되면 모두 0으로 출력된다.

 

BingInteger선언

BingInteger num = new BigInteger("500000")