CodingTest/백준
[C언어] 백준 - 4673번: 셀프 넘버
Daybreak21
2023. 2. 3. 16:29
#include <stdio.h>
int SelfNumber(int table[], int num) {
if (num < 10) num += num;
else if (num > 9 && num < 100) {
int Tens = num / 10;
int Ones = num % 10;
num = num + Tens + Ones;
}
else if (num > 99 && num < 1000) {
int Hundreds = num / 100;
int Tens = (num % 100) / 10;
int Ones = (num % 10) % 10;
num = num + Hundreds + Tens + Ones;
}
else {
int Thousands = num / 1000;
int Hundereds = (num % 1000) / 100;
int Tens = (num % 100) / 10;
int Ones = (num % 10) % 10;
num = num + Thousands + Hundereds + Tens + Ones;
}
//자신의 셀프넘버를 연속적으로 구하는 코드
if (num <= 10000) {
table[num] = 1;
SelfNumber(table, num);
}
return num;
}
int main() {
int table[10001] = {1};
for (int num = 1; num < 10000; num++) {
//table에서 값이 1이면 넘어감
if (table[num] != 1) {
SelfNumber(table, num);
printf("%d\n", num);
}
}
return 0;
}
여기에서도 table을 만들어서 구한 셀프넘버를 0 -> 1로 바꾸어주었다.
SelfNumber함수 안에서 Num가 10000을 넘지않을 때 까지 n, d(n), d(d(n)), d(d(d(n))), ...과 같은 재귀함수를 만들어주었다.
그리고 중복을 방지하기위해 n = 1로부터 만들어지는 모든 셀프넘버를 지우고 if (table[num] != 1) 문을 이용해서 지워진 수들은 그냥 넘어갔다. (아리스토테네스의 체 응용)
처음 문제의 알고리즘을 구상할 때 소수를 구하는 방법에서 많이 참고를 한 것 같다.
int self_number(int n)
{
int temp = n;
while(n>0) {
temp += n%10;
n/=10;
}
return temp; }
더 간단한 셀프넘버를 구하는 함수를 찾았음