Given two positive integers N and M., The task is to find the smallest divisor D of N such that gcd(D, M) > 1. If there are no such divisors, then print -1.
Input: N = 8, M = 10
Input: N = 8, M = 1
A naive approach is to iterate for every factor and calculate the gcd of the factor and M. If it exceeds M, then we have the answer.
Time Complexity: O(N * log max(N, M))
An efficient approach is to iterate till sqrt(n) and check for gcd(i, m). If gcd(i, m) > 1, then we print and break it, else we check for gcd(n/i, m) and store the minimal of them.
Below is the implementation of the above approach.
if (__gcd($m, $i) > 1)
// Check for gcd > 1
else if (__gcd($sec, $m) > 1)
$mini = min($sec, $mini);
// If gcd is m itself
if ($mini == $m)
// Driver code
$n = 8; $m = 10;
// This code is contributed by Code_Mech.
Time Complexity: O(sqrt N * log max(N, M))
- Smallest prime divisor of a number
- Find the k-th smallest divisor of a natural number N
- Smallest subarray such that all elements are greater than K
- Smallest number greater than or equal to N divisible by K
- Smallest Special Prime which is greater than or equal to a given number
- Smallest Greater (than S) String of length K whose letters are subset of S
- Smallest integer greater than n such that it consists of digit m exactly k times
- Max occurring divisor in an interval
- Maximum sum after repeatedly dividing N by a divisor
- Generating numbers that are divisor of their right-rotations
- Sum of greatest odd divisor of numbers in given range
- Find an integer X which is divisor of all except exactly one element in an array
- Greatest divisor which divides all natural number in range [L, R]
- Largest Divisor of a Number not divisible by a perfect square
- Queries to return the absolute difference between L-th smallest number and the R-th smallest number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.