Find Last Two Digits of 2^n in C++



In this problem, we are given a number N. Our task is to create a Program to find last two digits of 2^n in C++.

Problem Description

To find the last two digits. We will use only the product of the last two digits. And leave other things to make the calculation small.

Let’s take an example to understand the problem,

Input: N = 12 

Output: 96

Explanation

2^12 = 4096

Solution Approach

To solve the problem, a direct approach could be finding the value of 2^N and then finding the remainder when it is divided by 100.

Example

 Live Demo

#include <iostream>
using namespace std;
int findLastDigit(int N){
   int powerVal = 1;
      for(int i = 0; i < N; i++){
         powerVal *= 2;
      }
   return powerVal%100;
}
int main() {
   int N = 14;
   cout<<"The last two digits of 2^"<<N<<" is "<<findLastDigit(N);
   return 0;
}

Output

The last two digits of 2^14 is 84

This approach is not effective, as for large values of N the program will overflow.

A better approach is by only considering 2 digits from the values. And multiply it by two for every power.

For each in the case of 2^14, the last two digits are 84. We will multiply 84 by two instead of the whole number which will save calculations. So, (84*2)%100 = 68.

Example

 Live Demo

#include <iostream>
using namespace std;
int findLastDigit(int N){
   int powerVal = 1;
   for(int i = 0; i < N; i++){
      powerVal = (powerVal * 2)%100;
   }
   return powerVal;
}
int main() {
   int N = 15;
   cout<<"The last two digits of 2^"<<N<<" is "<<findLastDigit(N);
   return 0;
}

Output

The last two digits of 2^15 is 68
Updated on: 2020-10-09T07:40:41+05:30

578 Views

Kickstart Your Career

Get certified by completing the course

Get Started