VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-compute-mod-of-a-big-number/

⇱ How to compute mod of a big number? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to compute mod of a big number?

Last Updated : 10 Apr, 2023

Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer.

Examples : 

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) * 10) + (y (mod a))) mod a

where, x : left-most digit

y: rest of the digits except x.

for example: 

625 % 5 = (((6 % 5)*10) + (25 % 5)) % 5 = 0

Below is the implementation.

Thanks to utkarsh111 for suggesting the below solution.


Output
8

Time Complexity : O(|num|)

  • Time complexity will become size of num string as we are traversing once in num.

Auxiliary Space: O(1)


 

Comment