Find Last Digit Of a^b for Large Numbers | Practice | GeeksforGeeks

You are given two integer numbers, the base a and the index b. You have to find the last digit of ab.
 
Example 1:
Input:
a = "3", b = "10"
Output:
9
Explanation:
310 = 59049. Last digit is 9.
Example 2:
Input:
a = "6", b = "2"
Output:
6
Explanation:
62 = 36. Last digit is 6.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function getLastDigit() which takes two strings a,b as parameters and returns an integer denoting the last digit of ab.
 
Expected Time Complexity: O(|b|)
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= |a|,|b| <= 1000
Note:|a| = length of a and |b| = length of b. There will not be any test cases such that ab is undefined.
0
mayank20212 months ago
C++int getLastDigit(string a, string b) {              int zero_b=0;       for(int i=0; i<b.length(); i++)        {            if(b[i] !='0')             {                 zero_b=1;                 break;             }        }        if(zero_b==0) return 1;                int zero_a=0;       for(int i=0; i<a.length(); i++)        {            if(a[i] !='0')             {                 zero_a=1;                 break;             }        }        if(zero_a==0) return 0;       int last2;       if(b.length()>=2)        last2= (b[b.length()-2] -'0' ) *10 + (b[b.length()-1] -'0' );       else          last2= (b[b.length()-1] -'0' ) ;       //cout<<"--1--"<<last2<<endl;       if(last2 %4==0)        {            last2=pow(a[a.length()-1]-'0', 4);                    }        else        {            last2=last2%4;                        last2=pow(a[a.length()-1]-'0', last2);                    }        return last2%10;          }
0
rahulschauhan505 months ago
int getLastDigit(string a, string b) {
        // code here
        if(b=="0"){
            return 1;
        }
        int a1=a[a.size()-1]-'0';
        int b1=b[b.size()-1]-'0';
        if(b.size()>1){
            string ss="";
            ss+=b[b.size()-2];
            ss+=b[b.size()-1];
            b1=stoi(ss);
        }
        set<int>st;
        
        for(int i=1;i<=7;i++){
            int j=pow(a1,i);
            j=j%10;
            st.insert(j);
        }
        // for(auto i=st.begin();i!=st.end();i++){
        //     cout<<*i<<" ";
        // }
        int rem=b1%st.size();
        //cout<<endl<<rem<<endl;
        if(rem==0){
            return ((int)pow(a1,st.size()))%10;
        }
        else{
            return ((int)pow(a1,rem))%10;
        }
        
    }
0
ervishnu19945 months ago
static int getLastDigit(String a, String b) {       // code here       char[] x=a.toCharArray();       char[] y=b.toCharArray();       int power=0;      if(y.length<=2)       for(int i=0;i<y.length;i++){           power+=y[i]-48;           power*=10;       }       else       for(int i=y.length-2;i<y.length;i++){//last 2 digit separated           power+=y[i]-48;           power*=10;       }       power/=10;       // last two digit divided by 4 the number divide by 4       /*       last digit repeated same values;       greaterthan of 1:       1^0=1,1^1=1,1^2=1;       5^0=1,5^1=5,5^2=25;       6^0=1,6^1=6,6^2=36;       power 4 after repeated same last values:       2^0=1,2^1=2,2^2=4,2^3=8,2^4=16,2^5=32;       3^0=1,3^1=3,3^2=9,3^3=27,3^4=81,3^5=243;       7^0=1,7^1=7,7^2=49,7^3=343,7^4=2401,7^5=16809;       8^0=1,8^1=8,8^2=64,8^3=512,8^4=4096,8^5,32768;       */       if(x[x.length-1]-48==2||x[x.length-1]-48==3||x[x.length-1]-48==7||x[x.length-1]-48==8){           power%=4;           if(power==0)power=4;       }else if(x[x.length-1]-48==4||x[x.length-1]-48==9){           power%=2;           if(power==0)power=4;       }else if(x[x.length-1]-48==5||x[x.length-1]-48==6||x[x.length-1]-48==0||x[x.length-1]-48==1){           if(power>0)           return x[x.length-1]-48;       }       int result=1;       for(int i=0;i<power;i++){           result=(result*(x[x.length-1]-48))%10;       }       return result;   }
0
tshivansh445 months ago
                                      Java solution
class Solution {
    static int getLastDigit(String a, String b) {
        // code here
        // Return 1 if B is zero..
        if(b.equals("0"))
        {
            return 1;
        }
        //creation of HashMap and storing repeating digits..
        /*Using the concept that last digit repeats after every cycle
        of 4*/
    
        HashMap<Integer,ArrayList<Integer>> mp=new HashMap<>();
        for(int i=0;i<10;i++)
        {
         mp.put(i,new ArrayList<Integer>());   
        }
        for(int i=0;i<10;i++)
        {
            int k=i;
            for(int j=0;j<4;j++)
            {
                mp.get(i).add(k%10);
                k=k*i;
            }
        }
        /* After above for loop, Hash Map will be created which will contain value
        like 1:{1,1,1,1},2:{2,4,8,6},3:{3,9,7,1} */
        /* if b's length is 1, we can apply below concept,because
        b will not be that much large*/
       if(b.length()==1)
       {
         char lc=a.charAt(a.length()-1);
        int nlc=Character.getNumericValue(lc);  
         int ltd=Integer.parseInt(b)-1;
         return mp.get(nlc).get(ltd%4);
       }
       /* if b's length is above 2, we can use the property of divisiblity by
       4*/
        
        char lc=a.charAt(a.length()-1);
        int nlc=Character.getNumericValue(lc);
        String lt="";
        lt+=b.charAt(b.length()-2);
        lt+=b.charAt(b.length()-1);
        int ltd=Integer.parseInt(lt)-1;
        if(ltd%4==0)
        {
            return mp.get(nlc).get(0);
        }
        if(ltd%2==0)
        {
            return mp.get(nlc).get(2);
        }
        int f=4;
        int k=f;
        int count=1;
        while(ltd>k)
        {
            count++;
            k=f*count;
        }
        // System.out.println(k+" "+ltd);
        if((k-ltd)==3)
        {
          return mp.get(nlc).get(1);  
        }
        else
        {
            return mp.get(nlc).get(3);
        }
        
    }
};
+1
saurabhsharma295205 months ago
Time Complexity:      O(1)Space Complexity:      O(1)int getLastDigit(string a, string b)    {       int n = b.size();       if(b == "0") return 1;       int base = a.back()-48;       int power = stoi((n == 1) ? b : b.substr(n-2, n));       power %= 4;              unordered_map<int,vector<int>>mp;       mp.insert({0,  {0,0,0,0}});       mp.insert({1,  {1,1,1,1}});       mp.insert({2,  {2,4,8,6}});       mp.insert({3,  {3,9,7,1}});       mp.insert({4,  {4,6,4,6}});       mp.insert({5,  {5,5,5,5}});       mp.insert({6,  {6,6,6,6}});       mp.insert({7,  {7,9,3,1}});       mp.insert({8,  {8,4,2,6}});       mp.insert({9,  {9,1,9,1}});              return mp[base][(power == 0) ? 3 : power-1];          } 
-1
fungkwe5 months ago
O(1) with bit-wise operators and subtractions
0
atharvrustagi5 months ago
O(1) Time and O(1) Space Solution (Math based)
// last digits of powers of each number 
// (ex - powers of 3: 3 9 27 81 243 729...)
// pattern repeats after 4 numbers in powers of 3
vector<vector<int>> mp = {{0},
                          {1}, 
                          {2, 4, 8, 6}, 
                          {3, 9, 7, 1}, 
                          {4, 6}, 
                          {5},
                          {6},
                          {7, 9, 3, 1},
                          {8, 4, 2, 6},
                          {9, 1}};

class Solution {
  public:
    int getLastDigit(string a, string b) {
        if (b == "0")	return 1;
        int d = a.back() - '0';
        auto it = b.rbegin();
        // num = last 2 digits of b, or only last digit if |b|==1
        int num = *it - '0' + 3;    // 3 added due to mod adjustment
        ++it;
        if (it != b.rend())
            num += (*it - '0') * 10;
        return mp[d][num % mp[d].size()];
    }
};
-4
aakashmehta8805 months ago
O(1) Time Complexity O(1) Auxilliary space
int getLastDigit(string a, string b) {
        int A=stoi(a),B=stoi(b);
        if(B==0) return 1;
        if(A==0) return 0;
        int last=A%10;
        int x=0,y=0;
        
        x=pow(last,4);
        if(B%4!=0){
            y=pow(last,B%4);
            return (x*y)%10;
        }
        return x%10;
    }
+2
mastermind_5 months ago
( C++) Solution ~ O(|b|) Time
int getLastDigit(string a, string b) {
    int x = (a.back() - '0'), v = 0;
    if (b.size() == 1 && b[0] == '0')return 1;
    for (auto c : b)(v *= 10) %= 4, (v += (c - '0')) %= 4;
    return ((int)pow(x, (v == 0) ? 4 : v)) % 10;
}
+2
santoryuzoro05 months ago
class Solution { public:   int getLastDigit(string a, string b) {       int last_digit = a[a.length() - 1u] - '0';       if(b.length() == 1u && b[0] == '0') return 1;       vector<int> u(10);       for(int i = 0; i <= 9; i ++) {           int count = 0;           int dig = i;           do {               dig = (dig * i) % 10;               count ++;           } while(dig != i);           u[i] = count;       }       if(u[last_digit] == 1) return last_digit;       int mod = 0;       for(int i = 0; i < b.length(); i ++) {           mod = (mod * 10 + (b[i] - '0')) % u[last_digit];        }       // cout << mod << ' ' << u[last_digit] << '\n';       int answer = 1;       if(mod == 0) mod = u[last_digit];       while(mod --) {           answer = (answer * last_digit) % 10;       }       return answer;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.