이 절에서는 주어진 숫자가 아담의 수인지 아닌지를 검사할 수 있는 프로그램을 작성하는 방법을 볼 것이다. 코드를 살펴보기 전에 Adam 번호가 무엇인지 살펴보겠습니다.
아담수는 n이라고 하는 수이고, n의 제곱과 n의 역제곱이 역이면 그 수는 아담수이다. 예를 들어 숫자 13을 생각해 보겠습니다. 그 반대는 31입니다. 그런 다음 13의 제곱은 169이고 31의 제곱은 961입니다. 169와 961은 서로 반대이므로 숫자 13은 아담 수입니다.
주어진 번호가 아담 번호가 아닌지 확인하는 단계 -
- n번을 선택하세요.
- 숫자를 반대로 하여 m에 저장
- n의 제곱을 구하여 sq_n에 저장
- m의 제곱을 가져와서 sq_m에 저장
- sq_n과 sq_m의 역이 같은지 확인하세요.
예시
#include<iostream>
using namespace std;
int reverseNumber(int num) {
int res = 0;
while(num != 0) {
res = res * 10 + num % 10; //cut last digit and add into the result
num /= 10; //reduce the number
}
return res;
}
bool checkAdamNumber(int num) {
int rev_num = reverseNumber(num);
//get the square of the number and the reverse number
int sq_num = num * num;
int sq_rev_num = rev_num * rev_num;
//if the sq_num and sq_rev_num are reverse of each other, then they are Adam Number.
if(sq_num == reverseNumber(sq_rev_num)) {
return true;
}
return false;
}
main() {
int num;
cout << "Enter a number to check whether it is Adam number or not:";
cin << num;
if(checkAdamNumber(num)) {
cout << "The number is an Adam number";
} else {
cout << "The number is not an Adam number";
}
} 출력
Enter a number to check whether it is Adam number or not:13 The number is an Adam number
출력
Enter a number to check whether it is Adam number or not:25 The number is not an Adam number