[Geeks for Geeks] Mathematical manipulation

Mathematical manipulation

Given a number n, find the total numbers, less than or equal to n which have at-least one common factor with n other than 1.

  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
int gcd(int p, int q) {
if(!q) return p;
return gcd(q, p % q);
}
public:
int CommonFactor(int n){
int res = 0;
for(int i = 2; i <= n; i++)
if(gcd(n,i) != 1) res++;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/mathematical-manipulation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.