Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Euclidean Algorithm and it's Application. #86

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions C++/Algorithm/Euclidean.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Author : Aman Agarwal
Date : 10/10/2021
Description : Euclidean Algorithm and It's Application.

The Euclidean algorithm, discussed below,
allows to find the greatest common divisor
of two numbers a and b in "O(logmin(a,b))".
The algorithm was first described in Euclid's
"Elements" (circa 300 BC), but it is possible
that the algorithm has even earlier origins.

I used the same concept to solve CodeForces Round 81 D. Same GCDs
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the question link here, so that developers can check directly.

Overall Time Complexity : O(sqrt(n))
*/

#include <bits/stdc++.h>

using namespace std;

long long n, m, t, k = 0, a, l, p;

int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
cin >> t;
while (t--) {
cin >> a >> m;
n = m / gcd(a, m);
k = n;
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) {
k /= i;
k *= (i - 1);
while (n % i == 0) {
n /= i;
}
}
}
if (n != 1) {
k -= k / n;
}
cout << k << endl;
}
return 0;
}