ในปัญหานี้ เราได้ตัวเลข a และ b สองตัว งานของเราคือ ค้นหาตัวเลขสุดท้ายของ a^b สำหรับตัวเลขขนาดใหญ่
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
ป้อนข้อมูล: a =4 b =124
ผลลัพธ์: 6
คำอธิบาย:
ค่าของ a^b คือ 4.523128486 * 10 74
แนวทางการแก้ปัญหา
วิธีแก้ปัญหาขึ้นอยู่กับข้อเท็จจริงที่ว่าเลขชี้กำลังทั้งหมดของตัวเลขจะถูกทำซ้ำหลังจากค่าเลขชี้กำลัง 4 ค่า
ดังนั้น เราจะหาค่า b%4 ได้ นอกจากนี้ สำหรับค่าฐานใดๆ หลักสุดท้ายของกำลังจะถูกกำหนดโดยหลักสุดท้ายของค่าฐาน
ดังนั้นค่าผลลัพธ์จะถูกคำนวณเป็น
ค่าสุดท้ายของ a ^ (b%4)
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int calcModulus(char b[], int a)
{
int mod = 0;
for (int i = 0; i < strlen(b); i++)
mod = (mod * 10 + b[i] - '0') % a;
return mod;
}
int calcLastDigitInExpo(char a[], char b[]) {
int len_a = strlen(a), len_b = strlen(b);
if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')
return 1;
if (len_b == 1 && b[0] == '0')
return 1;
if (len_a == 1 && a[0] == '0')
return 0;
int exponent = (calcModulus(b, 4) == 0) ? 4 : calcModulus(b, 4);
int base = a[len_a - 1] - '0';
int result = pow(base, exponent);
return result % 10;
}
int main()
{
char a[] = "559", b[] = "4532";
cout<<"The last digit in of the value is "<<calcLastDigitInExpo(a, b);
return 0;
} ผลลัพธ์
The last digit in of the value is 1