Skip to content
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

Performance issue in Bigint::pow function #28

Open
JK000000 opened this issue Sep 29, 2018 · 0 comments
Open

Performance issue in Bigint::pow function #28

JK000000 opened this issue Sep 29, 2018 · 0 comments

Comments

@JK000000
Copy link

JK000000 commented Sep 29, 2018

In function Bigint::pow there are two indentical recruisive calls, that could be replaced by just one call
Consider changing

Bigint Bigint::pow(int const &power, std::map<int, Bigint> &lookup)
{
    if (power == 1) return *this;
    if (lookup.count(power)) return lookup[power];

    int closestPower = 1;
    while (closestPower < power) closestPower <<= 1;
    closestPower >>= 1;

    //here pow(power / 2, lookup) is called twice
    if (power == closestPower) lookup[power] = pow(power / 2, lookup) * pow(power / 2, lookup);
    else lookup[power] = pow(closestPower, lookup) * pow(power - closestPower, lookup);

    return lookup[power];
}

to

Bigint Bigint::pow(int const &power, std::map<int, Bigint> &lookup)
{
    if (power == 1) return *this;
    if (lookup.count(power)) return lookup[power];

    int closestPower = 1;
    while (closestPower < power) closestPower <<= 1;
    closestPower >>= 1;

    if (power == closestPower)
    {
        auto tmp = pow(power / 2, lookup);
        lookup[power] = tmp * tmp;
    }
    else
    {
        lookup[power] = pow(closestPower, lookup) * pow(power - closestPower, lookup);
    }

    return lookup[power];
}
g19fanatic pushed a commit to g19fanatic/bigint that referenced this issue Sep 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants