How to compute mod of a big number?


Given a big number ‘num’ represented as string and an integer x, find value of “num % x” or “num mod x”. Output is expected as an integer.


Input:  num = "12316767678678",  a = 10
Output: num (mod a) ≡ 8


The idea is to process all digits one by one and use the property that xy (mod a) ≡ ((x (mod a) * y) (mod a)). Below is C++ implementation.

Thanks to utkarsh111 for suggesting the below solution.

// C++ program to compute mod of a big number represented
// as string
using namespace std;

// Function to comput num (mod a)
int mod(string num, int a)
    // Initialize result
    int res = 0;

    // One by one process all digits of 'num'
    for (int i = 0; i < num.length(); i++)
         res = (res*10 + (int)num[i] - '0') %a;

    return res;

// Driver program
int main()
    string num = "12316767678678";
    cout << mod(num, 10);
    return 0;



Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

3 Average Difficulty : 3/5.0
Based on 4 vote(s)