# Check if a large number is divisible by 13 or not in C++

C++Server Side ProgrammingProgramming

Here we will see how to check a number is divisible by 13 or not. In this case the number is very large number. So we put the number as string.

A number will be divisible by 13, if the number satisfies the following situations −

• A number is divisible by 13 if and only if we get the alternating sum i.e. alternatively adding and subtracting of blocks of three numbers from right to left is divisible by 13. For example, 2911285 is divisible by 13 because the alternating sum of blocks of size 3 is 2 – 911 + 285 = -650 which is divisible by 13.
• A number is divisible by 13 if and only if the number is formed by adding last digit multiplied by 4 to rest is also divisible by 13. For example, consider 2353. Applying above rule, we get 235 + 3*4 = 247. In the next iteration, 24 + 7*4 = 52. Since 52 is divisible by 13, given number is divisible by 13.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isDiv13(string num){
int length = num.size();
if (length == 1 && num[0] == '0')
return true;
if (length % 3 == 1) { //when length is not divisible by 3, remainder is 1
num +="00";
length += 2;
} else if (length % 3 == 2){ //when length is not divisible by 3, remainder is 2
num += "0";
length += 1;
}
int sum = 0, p = 1;
for (int i = length - 1; i >= 0; i--) {
int set = 0;
set += (num[i--] - '0');
set += (num[i--] - '0') * 10;
set += (num[i] - '0') * 100;
sum = sum + set * p;
p *= (-1);
}
sum = abs(sum);
return (sum % 13 == 0);
}
int main() {
string num = "83959092724";
if(isDiv13(num)){
cout << "Divisible";
} else {
cout << "Not Divisible";
}
}

## Output

Divisible
Published on 22-Oct-2019 11:23:23