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


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

Updated on: 21-Oct-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements