Check if all prefixes of a number is divisible by remaining count of digits
Given a number N, the task is to check if for every value of i (0 <= i <= len), the first i digits of a number is divisible by (len – i + 1) or not, where len is the number of digits in N. If found to be true, then print “Yes”. Otherwise, print “No”.
Input: N = 52248.
- 5 is divisible by 5
- 52 is divisible by 4
- 522 is divisible by 3
- 5224 is divisible by 2
- 52248 is divisible by 1
Input: N = 59268
Output : No
Approach: The idea is to traverse all the prefixes of the given number and for each prefix, check if it is satisfies the condition or not.
Follow the steps below to solve the problem:
- Initialize a variable, say i as 1, to maintain the value of (len – i + 1).
- Iterate while n is greater than 0.
- If N is not divisible by i, then return false.
- Otherwise, divide N by 10 and increase the value of i by 1.
- Finally, return true.
Below is the implementation of the above approach.
Time Complexity : O(len) where len is the number of digits in N.
Auxiliary Space : O(1)
My Personal Notes arrow_drop_up
Please Login to comment...