How to compute mod of a big number?

3

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.

Examples:

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

Source: http://qa.geeksforgeeks.org/1061/given-big-number-form-string-how-do-take-mod-of-that-big-number

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
#include<iostream>
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;
}

Output:

8

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)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.