From ea18dfbaaa0340eb1f0da1e6533efb85aafdfd3d Mon Sep 17 00:00:00 2001 From: Bhavya M Modi <83846197+bhavyammodi@users.noreply.github.com> Date: Wed, 20 Oct 2021 09:23:33 +0530 Subject: [PATCH] Create fermats_little_theorem.cpp --- .../fermats_little_theorem.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 ALGORITHMS/Mathematical Algorithms/fermats_little_theorem.cpp diff --git a/ALGORITHMS/Mathematical Algorithms/fermats_little_theorem.cpp b/ALGORITHMS/Mathematical Algorithms/fermats_little_theorem.cpp new file mode 100644 index 00000000..dd4fa37c --- /dev/null +++ b/ALGORITHMS/Mathematical Algorithms/fermats_little_theorem.cpp @@ -0,0 +1,37 @@ +#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 theorem + cout << power(n, m, mod) << endl; + } + return 0; +}