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


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

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

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

  • add 7 * (last digit of the number calculated previous) to the truncated number

  • Repeat these steps as long as necessary.

17043, so 1704 + 7*3 = 1725
1725, so 172 + 7 * 5 = 207
207, this is 9 * 23, so 17043 is divisible by 23.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
bool isDivisibleBy23(long long int n) {
   while (n / 100) {
      int last = n % 10;
      n /= 10; // Truncating the number
      n += last * 7;
   }
   return (n % 23 == 0);
}
int main() {
   long long number = 1191216;
   if(isDivisibleBy23(number))
      cout << "Divisible";
   else
      cout << "Not Divisible";
}

Output

Divisible

Updated on: 21-Oct-2019

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements