- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find gcd(a^n, c) where a, n and c can vary from 1 to 10^9 in C++
We have to find the GCD of two numbers of which one number can be as big as (109 ^ 109), which cannot be stored in some data types like long or any other. So if the numbers are a = 10248585, n = 1000000, b = 12564, then result of GCD(a^n, b) will be 9.
As the numbers are very long, we cannot use the Euclidean algorithm. We have to use the modular exponentiation with O(log n) complexity.
Example
#include<iostream> #include<algorithm> using namespace std; long long power(long long a, long long n, long long b) { long long res = 1; a = a % b; while (n > 0) { if (n & 1) res = (res*a) % b; n = n>>1; a = (a*a) % b; } return res; } long long bigGCD(long long a, long long n, long long b) { if (a % b == 0) return b; long long exp_mod = power(a, n, b); return __gcd(exp_mod, b); } int main() { long long a = 10248585, n = 1000000, b = 12564; cout << "GCD value is: " << bigGCD(a, n,b); }
Output
GCD value is: 9
Advertisements