Find N % (Remainder with 4) for a large value of N in C++



In this problem, we are given a string num representing a large integer. Our task is to Find N % (Remainder with 4) for a large value of N.

Problem Description − we will be finding the remainder of the number with 4.

Let’s take an example to understand the problem,

Input

num = 453425245

Output

1

Solution Approach

A simple solution to the problem is by using the fact that the remainder of the number with 4 can be found using the last two digits of the number. So, for any large number, we can find the remainder by dividing the number’s last two digits by 4.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int calc4Mod(string num, int len) {
   int rem;
   if (len == 1)
      rem = num[0] - '0';
   else
      rem = (num[len - 2] - '0') * 10 + num[len - 1] - '0';
      return (rem % 4);
}
int main() {
   string num = "84525765476513";
   int len = num.length();
   cout<<"The remainder of the number with 4 is "<<calc4Mod(num, len);
   return 0;
}

Output

The remainder of the number with 4 is 1

Advertisements