From 08fa85d594aa18c0e6b6bdbda0eee2200b70a9bd Mon Sep 17 00:00:00 2001 From: Bhavya M Modi <83846197+bhavyammodi@users.noreply.github.com> Date: Fri, 22 Oct 2021 01:22:33 +0530 Subject: [PATCH 1/2] Create fermats_little_theorem.cpp --- .../C++/fermats_little_theorem.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp diff --git a/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp b/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp new file mode 100644 index 000000000..afa079a3f --- /dev/null +++ b/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp @@ -0,0 +1,38 @@ + +#include +#define ll long long int +// Compute (A^B)%mod +using namespace std; +ll power(ll a, ll b, ll mod) +{ + if (b == 0) + return 1; + ll ans = power(a, b / 2, mod); + ans %= mod; + ans = (ans * ans) % mod; + if ((b & 1) == 1) + return (ans * a) % mod; + return ans % mod; +} +ll stoi(string a, ll mod) +{ + ll ans = 0; + for (size_t i = 0; i < a.length(); i++) + ans = ((ans * 10) % mod + a[i] - '0') % mod; + return ans; +} +int main() +{ + ll n, m, mod = 1000000007; + ll t; + cin >> t; + string a, b; + while (t--) + { + cin >> a >> b; + n = stoi(a, mod); + m = stoi(b, mod - 1); // using fermats little theorem + cout << power(n, m, mod) << endl; + } + return 0; +} From 573969fe876adc8a6d458bfd8f49738395835b41 Mon Sep 17 00:00:00 2001 From: Bhavya M Modi <83846197+bhavyammodi@users.noreply.github.com> Date: Fri, 22 Oct 2021 01:25:48 +0530 Subject: [PATCH 2/2] Update fermats_little_theorem.cpp --- .../C++/fermats_little_theorem.cpp | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp b/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp index afa079a3f..995393d88 100644 --- a/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp +++ b/Algorithms/Miscellaneous/C++/fermats_little_theorem.cpp @@ -1,7 +1,7 @@ #include #define ll long long int -// Compute (A^B)%mod +// Compute (A^B)%mod, where A and B are can have <10^6 digits. using namespace std; ll power(ll a, ll b, ll mod) { @@ -36,3 +36,19 @@ int main() } return 0; } + +/* +Sample Input : +5 +3 2 +4 5 +7 4 +34534985349875439875439875349875 93475349759384754395743975349573495 +34543987529435983745230948023948 3498573497543987543985743989120393097595572309482304 +Sample Output : +9 +1024 +2401 +735851262 +985546465 +*/