C++ Coding Exercise: How to Check if a Large Integer is divisible by 11?


We all know that the 32-bit signed/unsigned integer takes 4 byte while 64-bit signed/unsigned integer takes 8 bytes to store. If there is a very big integer which is stored by a string e.g. “1234123412341289759687893247874” certainly we cannot hold this value exactly using the primitive data types. This article will show you a quick method to check if any large integer can be divided by 11.

A little Math

We have this integer: tex_18e2723af4e2155cbb7b7b110f2f16e5 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11?, so mathematically it can be expressed as: tex_725b1e98a55ffdae90e36a83eabb85fe C++ Coding Exercise: How to Check if a Large Integer is divisible by 11?

We know that 1, 100, 10000, 100000, .. tex_a273f61ac2f25731319c96a8b8978118 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11? modular 11 has the remainder 1 and 10, 1000, 100000… tex_49d021e6332b174bd49435a773227700 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11? modular 11 has the remainder -1.

Therefore, if n is odd: tex_6bde12e981260c4a8cdec8ec0180c209 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11? otherwise: tex_db6c63319d3f480b84156360c908dba6 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11?

So, to sum up, we just need to check the alternating sum of the digits: tex_cfd9f0ebe8d31469a2e9dc51c34890d9 C++ Coding Exercise: How to Check if a Large Integer is divisible by 11? to see if the sum (of course smaller and can be hold by primitive data types) can be divisible by 11.

For example, 3619 can by devisible by 11 because +3-6+1-9=-11 which is divisible by 11.

C++ Code

So, the following is the C++ code implementation based on the above idea and the STL::string type.

bool DivBy11(string num) {
    int sign = 1;
    int sum = 0;
    for (int i = 0; i < num.length(); i ++) {
        sum += (sign) * (num[i] - 48);
        sign *= -1;
    }
    return sum % 11 == 0;
}

–EOF (The Ultimate Computing & Technology Blog) —

525 words
Last Post: How to Cache Google QR Image using PHP?
Next Post: How to Improve SEO by NoIndexing Attachment and Pagination in WordPress?

The Permanent URL is: C++ Coding Exercise: How to Check if a Large Integer is divisible by 11? (AMP Version)

Leave a Reply