Check if a number is divisible by 41 or not in C++

C++Server Side ProgrammingProgramming

Here we will see one program, that can check whether a number is divisible by 41 or not. Suppose a number 104413920565933 is given. This is divisible by 41.

To check the divisibility, we have to follow this rule −

  • Extract the last digit of the number/truncated number every time

  • subtract 4 * (last digit of the number calculated previous) to the truncated number

  • Repeat these steps as long as necessary.

30873, so 3087 - 4*3 = 3075
3075, so 307 - 4 * 5 = 287
287, so 28 – 4 * 7 = 0
So, 30873 is divisible by 41.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
bool isDivisibleBy41(long long int n) {
   while (n / 100) {
      int last = n % 10;
      n /= 10; // Truncating the number
      n -= last * 4;
   }
   return (n % 41 == 0);
}
int main() {
   long long number = 104413920565933;
   if(isDivisibleBy41(number))
      cout << "Divisible";
   else
      cout << "Not Divisible";
}

Output

Divisible
raja
Published on 21-Oct-2019 13:50:26
Advertisements