ที่นี่เราจะดูวิธีหาหลักสองหลักสุดท้าย (Last Two Digits) คือ หลักหน่วยและหลักสิบ ของผลรวมแฟกทอเรียล N แฟกทอเรียล ดังนั้นถ้า N = 4 จะเป็น 1! + 2! + 3! + 4! = 33 หลักหน่วยคือ 3 และหลักสิบคือ 3 ผลลัพธ์จะเป็น 33
ถ้าเราดูอย่างชัดเจน แฟกทอเรียลของ N > 5 หลักหน่วยจะเป็น 0 ดังนั้นหลัง 5 จะไม่มีส่วนทำให้หลักหน่วยเปลี่ยน และหลัง N > 10 หลักสิบจะคงเป็น 0 สำหรับ N = 10 ขึ้นไป จะเป็น 00 เราสามารถสร้างตารางสำหรับ N = 1 ถึง 10 ของจำนวนแฟกทอเรียล
เราสามารถแก้ปัญหานี้โดยขั้นตอนเหล่านี้ -
- ถ้าค่า n น้อยกว่า 10 แล้ว (1! + 2! + ... + n!) mod 10
- ในทางกลับกัน เมื่อค่า n มากกว่าหรือเท่ากับ 10 แล้ว (1! + 2! + ... + 10!) mod 10 = 13
ตัวอย่างโค้ด
#include <iostream>
#include <cmath>
using namespace std;
int getTenAndUnitPlace(long long N) {
if (N <= 10) {
long long ans = 0, factorial = 1;
for (int i = 1; i <= N; i++) {
factorial = factorial * i;
ans += factorial;
}
return ans % 100;
}
return 13;
}
int main() {
for (long long i = 1; i < 15; i++) {
cout << "Ten and Unit place value of sum of factorials when N = " << i << " is: " << getTenAndUnitPlace(i) << endl;
}
}
ผลลัพธ์
Ten and Unit place value of sum of factorials when N = 1 is: 1 Ten and Unit place value of sum of factorials when N = 2 is: 3 Ten and Unit place value of sum of factorials when N = 3 is: 9 Ten and Unit place value of sum of factorials when N = 4 is: 33 Ten and Unit place value of sum of factorials when N = 5 is: 53 Ten and Unit place value of sum of factorials when N = 6 is: 73 Ten and Unit place value of sum of factorials when N = 7 is: 13 Ten and Unit place value of sum of factorials when N = 8 is: 33 Ten and Unit place value of sum of factorials when N = 9 is: 13 Ten and Unit place value of sum of factorials when N = 10 is: 13 Ten and Unit place value of sum of factorials when N = 11 is: 13 Ten and Unit place value of sum of factorials when N = 12 is: 13 Ten and Unit place value of sum of factorials when N = 13 is: 13 Ten and Unit place value of sum of factorials when N = 14 is: 13