Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
gbrand-salesforce opened this issue Mar 23, 2017 · 0 comments
Open

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

gbrand-salesforce opened this issue Mar 23, 2017 · 0 comments

Comments

@gbrand-salesforce
Copy link

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;
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant