Introduction
Problem Statement
We are given a number N. Our task is to find the minimum steps required to reduce a number 'N' to a prime number by subtracting with its highest divisor other than 1 and the N itself.
Sample test cases
Example 1:
Input: N = 14
Output: 1
Explanation
The highest divisor of 14 is 7, so N = (14 - 7) = 7 after subtracting with its highest divisor, 7 is a prime number.
Example 2:
Input: N= 28
Output: 2
Explanation
The highest divisor of 28 is 14, so N = (28 - 14) = 14 after subtracting with its highest divisor. Now, the highest divisor of 14 is 7, so N = (14 - 7) = 7 and 7 is a prime number.
Also see, Euclid GCD Algorithm
Approach
The idea is straightforward: we find the highest divisor of N, subtract N with it and increment the count of steps.
If the resulting number is prime after subtracting N with its highest divisor, print the number of steps required till now. Else repeat the above process with the resulting number in place of N.
Steps of algorithm
- If the given number is prime, return 0 as it is already a prime number.
- Create a variable mnm_steps = 0 to store the number of minimum steps required.
- Initialise a variable i = 2 and run a while loop till N!=i.
- Run another while loop inside the previous while loop. At every step, subtract N with its highest divisor and check the resulting number is prime or not.
- If the resulting number is prime, return the value of mnm_steps.
- Increment the value of i by 1.
- Finally, return the value of mnm_steps.
Let's understand the above approach with an example:
Given number = 28
Initially mnm_steps = 0
-
The highest divisor of N = 28 is 14.
-
Subtract 28 with 14 and increment the value of mnm_steps by 1, N = (28 - 14) = 14 and mnm_steps = 1.
-
14 is not a prime number, so we repeat the above steps with N = 14.
-
The highest divisor of N = 14 is 7.
-
Subtract 14 with 7 and increment the value of mnm_steps by 1, N = (14 - 7) = 7 and mnm_steps = 2.
- Now, 7 is a prime number. Return the value of mnm_steps = 2.