เราได้รับตัวแปรจำนวนเต็มบวก num และ x งานคือคำนวณ num^x แบบเรียกซ้ำ (recursive) จากนั้นบวกตัวเลขแต่ละหลักของผลลัพธ์จนได้หลักเดียว (digital root) และนำค่าหลักเดียวนั้นมาเป็นผลลัพธ์
ตัวอย่างการทำงาน (Input/Output)
ตัวอย่างที่ 1
Input: int num = 2345, int x = 3
Output: Recursive sum of digit in n^x, where n and x are very large are: 8
คำอธิบาย: 2345^3 = 12,895,213,625 → บวกหลัก: 1+2+8+9+5+2+1+3+6+2+5 = 44 → 4+4 = 8 (ได้หลักเดียว)
ตัวอย่างที่ 2
Input: int num = 3, int x = 3
Output: Recursive sum of digit in n^x, where n and x are very large are: 9
คำอธิบาย: 3^3 = 27 → 2+7 = 9 (ได้หลักเดียวทันที)
อัลกอริทึมที่ใช้ (ใช้คุณสมบัติ Digital Root และ Modulo 9)
- รับค่า
numและxส่งให้ฟังก์ชันRecursive_Digit(num, x) - ภายใน
Recursive_Digit(num, power):- คำนวณ
total = total_digits(num)(digital root ของฐาน) temp = power % 6(ใช้รอบของ modulo 9)- เงื่อนไขพิเศษ: ถ้า
total == 3 || total == 6และpower > 1คืน 9 - ถ้า
power == 1คืนtotal - ถ้า
power == 0คืน 1 - ถ้า
temp == 0คืนtotal_digits(pow(total, 6)) - มิฉะนั้น คืน
total_digits(pow(total, temp))
- คำนวณ
- ฟังก์ชัน
total_digits(long num)คำนวณ digital root:- ถ้า
num == 0คืน 0 - ถ้า
num % 9 == 0คืน 9 - มิฉะนั้น คืน
num % 9
- ถ้า
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
long total_digits(long num) {
if (num == 0) return 0;
if (num % 9 == 0) return 9;
else return num % 9;
}
long Recursive_Digit(long num, long power) {
long total = total_digits(num);
long temp = power % 6;
if ((total == 3 || total == 6) & power > 1) {
return 9;
} else if (power == 1) {
return total;
} else if (power == 0) {
return 1;
} else if (temp == 0) {
return total_digits((long)pow(total, 6));
} else {
return total_digits((long)pow(total, temp));
}
}
int main() {
int num = 2345;
int x = 98754;
cout << "Recursive sum of digit in n^x, where n and x are very large are: " << Recursive_Digit(num, x);
return 0;
}
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:
Recursive sum of digit in n^x, where n and x are very large are: 1