Skip to content

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

@gbrand-salesforce

Description

@gbrand-salesforce

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;
    
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions