coding-questions icon indicating copy to clipboard operation
coding-questions copied to clipboard

Calculate (m^n)%(10^k)

Open gbrand-salesforce opened this issue 8 years ago • 0 comments
trafficstars

I don't know how big you expect m to be, but if m is an int, n is long long and k is int - there's no need for simulating a big number via a string (also, there are better ways to create big numbers).

The solution code can be

long long get_m_to_nth_mod_10_to_kth(int m, long long n, int k)
{
    long long exponent = std::pow(10L, k);
    if (n == 1)
        return m % exponent;
    if (n%2) //odd
        return (get_m_to_nth_mod_10_to_kth(m,n-1,k) * m) % exponent;
    else
        return  static_cast<long long>(std::pow(get_m_to_nth_mod_10_to_kth(m,n/2,k), 2L)) % exponent;
    
}

gbrand-salesforce avatar Mar 23 '17 23:03 gbrand-salesforce