指数求模

指数幂求模

c o m u p t e   a j   m o d   p comupte\ a^{j}\ mod \ p comupte aj mod p

Formular

(pq) mod N = ((p mod N)*(q mod N)) mod N

a t = { a ( a j / 2 ) 2 j   i s   o d d   n u m b e r ( a j / 2 ) 2 j   i s   e v e n   n u m b e r a^{t}=\left\{ \begin{aligned} a(a^{j/2})^{2}& & j \ is\ odd\ number\\ (a^{j/2})^{2} && j \ is \ even \ number \end{aligned} \right. at={a(aj/2)2(aj/2)2j is odd numberj is even number

Code Implementation

//
//  main.cpp
//  ModularExponent
//
//  Created by Ronald on 2018/10/16.
//  Copyright © 2018 Ronald. All rights reserved.
//

#include <iostream>
#include <stack>

using namespace std;

//compute a^j%p
int modular_exponent_re(int a,int j, int p){
    if(p<0){
        return -1;
    }
    if(j==0){
        return 1;
    }else{
        int z = modular_exponent_re(a, j/2, p);
        if(j%2==0){
            return ((z%p)*(z%p))%p;
        }else{
            return (a*(z%p)*(z%p))%p;
        }
    }
}

int modular_exponent(int a,int j,int p){
    if(j<0){
        return -1;
    }
    if(j==0){
        return 1;
    }else{
        stack<int> s;
        int result = a;
        while(j){
            s.push(j);
            j=j/2;
        }
        
        while (s.size()>1) {
            int t = s.top();
            s.pop();
            result = ((result%p)*(result%p))%p;
            if (s.empty()) {
                break;
            }
            if (t*2 != s.top()) {
                result = ((a%p)*result)%p;
            }
        }
        return result;
    }
}

int modular_exponent1(int a,int j,int p){
    if(j<0){
        return -1;
    }
    if(j==0){
        return 1;
    }else{
        int result = 1;
        
        while (j>0) {
             if (j%2!=0) {
                result = (a*result)%p;
            }
           // result = ((result%p)*(result%p))%p;
           //a=(a*a)%p
           a = a%p;
           a=(a*a)%p;
           j=j/2;
        }
        return result;
    }
}

s=1
if j is odd s=s*a
( a 2 ) j / 2 (a^{2})^{j/2} (a2)j/2

int modular_exponent_trick(int a,int j,int p){
    int s = 1;
    while(j){
        if (j%2 != 0) {
            s = (s*a)%p;
        }
        a = (a*a)%p;
        j=j/2;
    }
    return s;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    std::cout << modular_exponent_re(3, 10, 31)<<endl;
    std::cout << modular_exponent(3, 10, 31)<<endl;
    std::cout << modular_exponent_trick(3, 10, 31)<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值