Check if a number is divisible by all prime divisors of another number in C++

C++Server Side ProgrammingProgramming

Suppose there are two numbers. We have to check whether a number is divisible by all of the prime factors or the second number or not. Suppose a number is 120. The prime factors are {2, 3, 5}, another number is 75, here the prime factors are {3, 5}. As 120 is divisible by 3 and 5 also, then the decision is yes.

If one number is 1, then it has no prime divisors, so answer is True. Otherwise we have to find the GCD of these two numbers. If GCD is 1, then they are co-prime. So answer is false. If GCD is > 1, then GCD contains prime divisor, which divide x also (x as first number). If we have all unique prime divisor iff second number y / GCD has such unique prime divisor. We have to find uniqueness for pair (x, y/GCD) using recursion.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
bool isDivisible(int a, int b) {
   if (b == 1)
      return true;
   int gcd = __gcd(a, b);
   if (gcd == 1)
      return false;
      return isDivisible(a, b / gcd);
}
int main() {
   int a = 120, b = 75;
   if (isDivisible(a, b))
      cout << a << " can be divisible by all prime factors of " << b;
   else
      cout << a << " can NOT be divisible by all prime factors of " << b;
}

Output

120 can be divisible by all prime factors of 75
raja
Published on 22-Oct-2019 11:43:57
Advertisements