VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-number-divisible-prime-divisors-another-number/

⇱ Check if a number is divisible by all prime divisors of another number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 2 May, 2025

Given two positive integers x and y, the task is to determine whether x is divisible by all the prime divisors of y. That means, every prime number that divides y should also divide x. If this condition holds true, print Yes, otherwise print No.

Examples:

Input: x = 120, y = 75
Output: Yes
Explanation: The prime divisors of 75 are 3 and 5. Since 120 is divisible by both 3 and 5, the answer is Yes.

Input: x = 15, y = 6
Output: No
Explanation: The prime divisors of 6 are 2 and 3. Although 15 is divisible by 3, it is not divisible by 2. Hence, the answer is No.

Input: x = 210, y = 30
Output: Yes
Explanation: The prime divisors of 30 are 2, 3, and 5. Since 210 is divisible by all of them, the answer is Yes.

[Expected Approach - 1] Finding All Prime Divisors of y

The idea is to check all prime divisors of y and verify if x is divisible by each of them. The thought process is to iterate from 2 to sqrt(y), and for every factor i, check if it's a prime divisor by dividing y completely. If x is not divisible by any such prime, we return false. After the loop, if any prime > sqrt(y) remains in y, we handle it separately.


Output
Yes

Time Complexity: O(sqrt(y)), we check up to sqrt(y) for factors.
Space Complexity: O(1), no extra space or data structures used.

[Expected Approach - 2] Using the GCD Concept

The idea is to check if all prime divisors of y divide x by cleverly using the GCD (Greatest Common Divisor) concept. Instead of finding and checking each prime factor individually, we repeatedly remove common factors (given by GCD) from y.

The thought process is, if we keep dividing y by gcd(x, y), we are stripping away the part of y that is also in x. If after all removals, y becomes 1, then all prime factors of y were present in x.

The key observation is: any prime factor of y that is not in x will remain in y, preventing it from reaching 1. So, if y ≠ 1 at the end, it means x does not include all prime divisors of y.


Output
Yes

Time Complexity: O(log(y) * log(x)), since each GCD operation takes O(log x) time (as x remains constant) and we may perform this operation up to O(log y) times (as y gets reduced each time).
Space Complexity: O(1), Uses constant space without any additional data structures.

Comment
Article Tags: