C/C++实现大数模指数运算-二进制算法(a^e mod m 当e特别巨大时...)
来源:互联网 发布:淘宝主营业务是什么 编辑:程序博客网 时间:2024/05/21 15:41
模指数运算: 已知a, e, m, 计算a^e mod m ➡ a: 底数, e: 指数, m: 模数
解决已知a, e, m, 计算a^e mod m 指数过大运算结果超出固定分配空间能够存储的最大值的问题。
可应用于公钥密码体制, 哈希函数等密码学问题中。
示例: 计算2^90 mod 13
当e很大时, a^e溢出: 运算结果超出固定分配空间能够存储的最大值
solution:
代码实现:
#include <iostream>#include <math.h>#include <string>using namespace std;int main(){ int base, exponent, modulo;cin >> base >> exponent >> modulo;int a = base;//底数int e = exponent;//指数int m = modulo;//模数long long int s = 1, ti[1000] = {}, ai[1000] = { 0 }, at[1000] = {};string Binary_e;while (e != 0)//用于把指数e转换为二进制Binary_e{Binary_e = (char)(e % 2 + '0') + Binary_e;e >>= 1;//val_/=2;}int sz = Binary_e.size();//字符串长度szfor (int i = 0; i < sz; i++){ti[i] = Binary_e[i] - '0';//把二进制字符串Binary_e存入整型数组ti[]中}cout << endl;at[0] = a;for (int i = 0; i<sz; i++){int j = i;at[j + 1] = pow(at[j], 2);at[j + 1] = at[j + 1] % m;at[j + 1] = (at[j+1] + m) % m;//记录n个 a的从2-2^n的模指数ai[i] = ti[sz - i -1] * at[i];if (ti[sz - i - 1] == 1){s = (ai[i] * s) % m;//把存在的模后的数 累乘}}s = (s + m) % m;cout << "7^256 mod 13 = "<<s << endl;system("pause");return s;}
VS2015编译环境下:
0 0
- C/C++实现大数模指数运算-二进制算法(a^e mod m 当e特别巨大时...)
- 快速求m^e mod n算法
- 模取幂运算 (a^b mod c)
- 模取幂运算 (a^b mod c)
- 模取幂运算 (a^b mod c)
- 快速幂算法 取余运算 a^b mod c
- cf(416 A,B,C,E)
- FZU 1759-Super A^B mod C(指数循环节)
- 关于 A^x = A^(x % Phi(C) + Phi(C)) (mod C) 的若干证明(指数循环节)
- [转]模取幂运算 (a^b mod c)
- 模取幂运算 计算a^b mod c
- Super A^B mod C(指数循环节+欧拉函数)
- E/C
- 【AC大牛】【关于 A^x = A^(x % Phi(C) + Phi(C)) (mod C) 的若干证明】【指数循环节】
- EXECUTE IMMEDIATE
- 求C(n,m)%mod
- CS R12 C(排序),D(思维(二进制)),E(计数,分类大讨论)
- A^B Mod C(快速幂算法)
- 我要努力!!!!!!!!
- OpenGL Superbible 7 02 Our First OpenGL Program
- win10手动编译opencv3.2+contrib
- a bit与a little 的区别
- 在vim中执行shell指令
- C/C++实现大数模指数运算-二进制算法(a^e mod m 当e特别巨大时...)
- adfasfasfsa#随机字母=50#sfwradfasfasfsa#随机大写字母=20#sfwradfasfasfsa#随机汉字=60#sfwr#随机汉字=10#石家庄石家庄
- Aanya’s Day at the Beach
- vim代码自动对齐
- 线性同余算法 (LCG)
- 确定性素性测试思想之Eratosthenes筛选法
- adfasfasfsaRKEKmnMRxUZKpxTgBEIqpNytOCOmhwUEZxkSsZgBuvkWqZtPYYoAsfwradfasfasfsaKVQCFFYRMMSAZKSVGAUNKD
- adfasfasfsaMmQZmINbkaRCnFngxbsGGXSgMpbRrMgQmMfLzwPHbdOTPVvoIDZFsfwradfasfasfsaZXTUGSGYQXRLWAINNNQAGS
- 第四章 碎片的生命周期