UVa 10212 - The Last Non-zero Digit Solution

#include <iostream>
int modp(int a,int x){
    int ans=1;
    while(x>0){
        if(x&1){
            ans*=a;
            ans%=10;
        }
        a*=a;
        a%=10;
        x>>=1;
    }
    return ans;
}
using namespace std;
int main(){
    int n,m;
    while(cin>>n>>m){
        long long ans=1;
        int five=0,two=0;
        for(int i=n;i>n-m;i--){
            int j=i;
            while(j%5==0)
                j/=5,five++;
            while(j%2==0)
                j>>=1,two++;
            ans*=j;
            ans%=10;
        }
        if(two>=five)
            ans*=modp(2,two-five);
        else
            ans*=modp(5,five-two);
        cout<<ans%10<<endl;
    }
}

Comments