ในส่วนนี้เราจะมาดูวิธีการเขียนโปรแกรมที่สามารถตรวจสอบว่าหมายเลขที่กำหนดเป็นหมายเลขอดัมหรือไม่ ก่อนดำดิ่งลงไปในโค้ด เรามาดูกันก่อนว่าหมายเลขอดัมคืออะไร
เลขอาดัมเป็นตัวเลขที่บอกว่า n แล้วถ้ากำลังสองของ n และกำลังสองของส่วนกลับของ n กลับด้านกัน ตัวเลขนั้นก็คือเลขอาดัม ตัวอย่างเช่น ให้เราพิจารณาตัวเลข 13 ที่กลับด้านคือ 31 จากนั้นกำลังสองของ 13 คือ 169 และกำลังสองของ 31 คือ 961 169 และ 961 อยู่ตรงข้ามกัน ดังนั้นเลข 13 จึงเป็นเลขอาดัม
ขั้นตอนในการตรวจสอบว่าหมายเลขที่กำหนดเป็นหมายเลขอดัมหรือไม่ −
- เอาเลข n
- ย้อนกลับตัวเลขและเก็บไว้ใน m
- รับ Square of 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