Mod power或者逻辑问题

时间:2014-05-06 21:57:05

标签: c++ modulus greatest-common-divisor

以下是我改编的一些代码,用于处理euler totient函数和power mod函数。每个nf2始终为3,而不是各种数字。有人看到错误吗? phi(n)modpow(n)似乎都很好。

#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b != 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

int phi(int n)
{
    int x = 0;
    for (int i=1; i<=n; i++)
    {
        if (gcd(n, i) == 1)
            x++;
    }
    return x;
}

int modpow(int base, int exp, int mod) // from stackoverflow
{
    base %= mod;
    long long result = 1;
    while (exp > 0)
    {
        if (exp & 1)
            result = (result * base) % mod;
        base = (base * base) % mod;
        exp >>= 1;
    }
    return result;
}

int f2(int n) // f(f(n)) mod n
{
    long long a = modpow(2, n, phi(n)) + 1;
    return (modpow(2, a, n) + 1) % n;
}

// ...

int main()
{
    int n = 520001;
    while (true)
    {
        cout << "f2 " << f2(n) << endl;
        if (f2(n) == 0)
        {
            // ...
        }

        n += 2;
    }
    return 0;
}

f2(n)的值应为9, 458278, 379578, ...

1 个答案:

答案 0 :(得分:0)

如果base> gt = = 65536,

base * base将超过int的大小。尝试此修复,似乎有效:

int modpow(int base, int exp, int mod) // from stackoverflow
{
    base %= mod;
    long long result = 1;
    while (exp > 0)
    {
        if (exp & 1)
            result = (result * base) % mod;
        base = (int)(((long long)base * (long long)base) % mod);
        exp >>= 1;
    }
    return (int) result;
}