ที่นี่เราจะดูวิธีหาหลักหน่วย (Unit Place) ของผลรวมแฟกทอเรียล N แฟกทอเรียล ดังนั้นถ้า N คือ 3 แล้วหลังจากได้ผลรวม เราจะได้ 1! + 2! + 3! = 9 นี่จะเป็นผลลัพธ์ สำหรับ N = 4 จะเป็น 1! + 2! + 3! + 4! = 33 ดังนั้นหลักหน่วยคือ 3 หากเราดูอย่างชัดเจน แฟกทอเรียลของ N > 5 หลักหน่วยจะเป็น 0 ดังนั้นหลังจาก 5 จะไม่มีส่วนทำให้หลักหน่วยเปลี่ยน สำหรับ N = 4 ขึ้นไป จะเป็น 3 เราสามารถสร้างตารางสำหรับหลักหน่วย และจะนำไปใช้ในโปรแกรม
ตัวอย่างโค้ด
#include <iostream>
#include <cmath>
using namespace std;
double getUnitPlace(int n) {
int placeVal[5] = {-1, 1, 3, 9, 3};
if (n > 4) {
n = 4;
}
return placeVal[n];
}
int main() {
for (int i = 1; i < 10; i++) {
cout << "Unit place value of sum of factorials when N = " << i << " is: " << getUnitPlace(i) << endl;
}
}
ผลลัพธ์
Unit place value of sum of factorials when N = 1 is: 1 Unit place value of sum of factorials when N = 2 is: 3 Unit place value of sum of factorials when N = 3 is: 9 Unit place value of sum of factorials when N = 4 is: 3 Unit place value of sum of factorials when N = 5 is: 3 Unit place value of sum of factorials when N = 6 is: 3 Unit place value of sum of factorials when N = 7 is: 3 Unit place value of sum of factorials when N = 8 is: 3 Unit place value of sum of factorials when N = 9 is: 3