2013-02-16 146 views
0

我有一个程序使用模块求幂来计算7^644 mod 645,11^644 mod 645,3^2003 mod 99,123^1001 mod 101.我遵循模块求幂的规则,然后当我编译我的结果是错误的,输出的结果应该是436,1,22,27,但是我的输出是关闭的。当我运行我的答案是643,655,20,39模块化算法计算错误

这是我的代码:

int Modulo(int b, int e, int m) 
{ 

int remainder;//set the remainder of the procedure 
int x = 1;// modular initially sets x = 1 

//while loop to request the multiplication 
while (e != 0) 
{ 

    remainder = e % 2; 
    e = e/2; 

    //Algorithm steps 
    if(remainder == 1)//if remainder = 1 
    x = (x * b) % m;//then x = (x · power) % m 
    b = (b * b) % m;//power = (power * power) % m 

} 
return x; 


} 
int main() 
{ 

    int b, e, m, modulo;//declares the variables 
    start:cout<<"Enter the base: ";//output for base 
    cin>>b; 

    cout<<"Enter the exponent: ";//output for exponent 
    cin>>e; 

    cout<<"Enter the number of modular: ";//output for mod 
    cin>>m; 

    modulo = b^e % m;//requesting the formula of Modular Exponentiation 
    cout<<"The answer is \n"<<modulo<<endl; 
    cin.get(); 
    // I create if statement to allow the user to restart the application 
//enter new value to see the different output 
    char c; 
    cout<<"Would you like to enter a new value? yes or no "; 
    cin>> c; 
    if((c == 'Y') ||(c == 'y'))goto start ;//start is the label in the start of program 
    return 0; 
} 
+0

呃......你知道你没有使用你的Modulo函数,对吗? – Xymostech 2013-02-16 05:12:32

+0

我没有意识到这一点。 – 2013-02-16 05:14:20

+0

如果你使用你的功能,它是否工作? – Xymostech 2013-02-16 05:21:32

回答

0

对于它的价值,我会写的代码是这样的(经过测试并产生正确的结果至少我已经试过值):我已经试过为你的代码没有使用相同的名称

unsigned Modulo(unsigned b, unsigned e, unsigned m) { 
    unsigned x = 1; 

    while (e > 0) { 
     if (e & 1) 
      x = x * b % m; 
     e >>= 1; 
     b = b * b % m; 
    } 
    return x; 
} 

注 - 许多人不打我的最好的(甚至是很不错的)虽然选择。 Modulo在我看来似乎是一个特别可怜的名字。我宁愿像pow_mod这样的东西,至少暗示它在做什么(其中Modulo几乎完全是误导)。