Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ค้นหาหลักหน่วยของผลรวมของแฟคทอเรียล N โดยใช้ C++


ในที่นี้เราจะมาดูวิธีหาเลขหลักหน่วยของผลรวมของแฟคทอเรียล N ดังนั้นถ้า N เป็น 3, หลังจากที่ได้ผลรวม, เราจะได้ 1! + 2! +3! =9 นี่จะเป็นผลลัพธ์ สำหรับ N =4 มันจะเป็น 1! + 2! +3! +4! =33. ดังนั้นตำแหน่งของหน่วยคือ 3 ถ้าเราเห็นสิ่งนี้ชัดเจน ดังนั้นในฐานะแฟกทอเรียลของ N> 5 ตำแหน่งของหน่วยคือ 0 ดังนั้นหลังจาก 5 จะไม่มีส่วนในการเปลี่ยนตำแหน่งของหน่วย สำหรับ N =4 และมากกว่านั้น จะเป็น 3 เราสามารถสร้างแผนภูมิสำหรับตำแหน่งหน่วยและที่จะใช้ในโปรแกรมได้

ค้นหาหลักหน่วยของผลรวมของแฟคทอเรียล N โดยใช้ C++

ตัวอย่าง

#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