1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class P034 { public static void main(String args[]) { System.out.println(run()); } public static String run() { int count = 0; for(int i = 10; i <= 1000000; i++) { int temp = i; int sum = 0; do { sum += factorial(temp%10); temp /= 10; } while(temp > 0); if(sum == i) { count += i; } } return Integer.toString(count); } public static int factorial(int n) { int res = 1; for(int i = 2; i <= n; res *= i++); return res; } } | cs |
9행:
범위를 어떻게 할 지 몰라서 검색했음.(https://opentutorials.org/module/3075/18760)
13~16행:
10 이상 1000000 이하 자연수에 대해 (자릿수)!의 합을 구한다.
temp%10 은 현재 수의 일의 자리 수가 되고 temp /= 10 을 하면 일의 자리 수를 잘라내게 된다.
루프 진입 전 temp 값이 1863이라 하면 다음과 같이 진행된다.
sum = sum + (1863%10)!; -> sum = sum + 3!;
temp = 1863/10; -> temp = 186;
sum = sum + (186%10)!; -> sum = sum + 6!;
temp = 186/10; -> temp = 18;
sum = sum + (18%10)!; -> sum = sum + 8!;
temp = 18/10; -> temp = 1;
sum = sum + (1%10)!; -> sum = sum + 1!;
temp = 1/10; -> temp = 0;
18행:
13 ~ 16행을 거쳐 계산된 합이 원래 수인 i 와 같으면 count 에 i 를 더한다.
이 count 가 문제에서 요구하는 답이 된다.
26~31행:
팩토리얼 계산. parameter로 주어진 n 에 대해 n! 값을 구한다.
28행에서 res *= i++ 는 후위 연산자가 쓰였기 때문에 res 에 i 를 곱한 후 i 값이 1 증가한다.
res 를 1로 초기화하고 이런 과정을 i = 2, 3, ..., n 에 대해 반복하면 res 에는 n! 값이 저장된다.
여기까지 쓰다 보니 9행의 반복문의 i 를 문자열로 바꾼 다음 한 문자씩 숫자로 바꾸면서 팩토리얼을 계산한 후 더해도 될 것 같아서 해봤더니 됐다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class P034 { public static void main(String args[]) { System.out.println(run()); } public static String run() { int count = 0; for(int i = 10; i <= 1000000; i++) { String s = Integer.toString(i); int sum = 0; for(int j = 0; j < s.length(); j++) { sum += factorial(s.charAt(j) - '0'); } if(sum == i) { count += i; } } return Integer.toString(count); } public static int factorial(int n) { int res = 1; for(int i = 2; i <= n; res *= i++); return res; } } | cs |
'0'(문자 0)을 빼지 않고 바로 factorial 메소드를 호출하면 계산을 하면 정수 값의 팩토리얼이 아닌 숫자의 아스키 코드 값의 팩토리얼이 되므로 0!, 1!, ..., 9!이 아닌 48!, 49!, ... 57!이 된다. 따라서 '0'을 빼서 실제 숫자 값의 팩토리얼이 되도록 한다.
실행 시간은 별 차이 없는 것 같아서 그냥 다양한 방법으로 풀어본 것에 의미를 두기로 했다.
'Programming > Solutions' 카테고리의 다른 글
[Project Euler] Problem 092 (0) | 2021.01.11 |
---|---|
[Project Euler] Problem 036 (0) | 2021.01.11 |
[Project Euler] Problem 037 (0) | 2019.07.25 |
[BAEKJOON] 2747번 (0) | 2019.06.18 |
[BAEKJOON] 15552번 (0) | 2019.06.17 |