Check if a number is divisible by 31 or not
Given a number N, the task is to check whether the number is divisible by 31 or not.
Input: N = 1922
31 * 62 = 1922
Input: N = 2722400
Approach: The divisibility test of 31 is:
- Extract the last digit.
- Subtract 3 * last digit from the remaining number obtained after removing the last digit.
- Repeat the above steps until a two-digit number, or zero, is obtained.
- If the two-digit number is divisible by 31, or it is 0, then the original number is also divisible by 31.
If N = 49507 Step 1: N = 49507 Last digit = 7 Remaining number = 4950 Subtracting 3 times last digit Resultant number = 4950 - 3*7 = 4929 Step 2: N = 4929 Last digit = 9 Remaining number = 492 Subtracting 3 times last digit Resultant number = 492 - 3*9 = 465 Step 3: N = 465 Last digit = 5 Remaining number = 46 Subtracting 3 times last digit Resultant number = 46 - 3*5 = 31 Step 4: N = 31 Since N is a two-digit number, and 31 is divisible by 31 Therefore N = 49507 is also divisible by 31
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.