算法之运算 模的指数运算
模的指数运算
- 真言
家人万岁,亲情万岁。
- 引言
哎呀,放假了,回家了,村里建设挺好哈,晚上大娘婶婶出来跳舞了,我还在coding,有鸡叫的日子真好,喜欢农村,I‘m a 农民,还不是村干部!
- 模的指数运算
原来模的功能是这么的强大,以前没有太在意它,实在是愧疚呀。模赋予了单位很大的意义,使得大数据可以被我们处理,这就是我对模的理解。问题定义:给定x和y,计算x的y次方模N的值,其中N有数百位长。算法如下(递归的算法)原理如下
- 实验
- 代码
- 只要算法是递归的,我都会在转换成非递归的算法,同时给大家。
- test1.cpp
-
[cpp] view plaincopy
- #include<iostream>
- #include<stack>
- using namespace std;
- // function modexp in recursion
- int modexp_re(int x,int y,int N);
- // function modexp without recursion
- int modexp_nonre(int x,int y,int N);
- int const N = 10000 ;
- // function main
- int main()
- {
- int a,b,i = 0;
- while(i < 100)
- {
- a = rand()%10000;
- b = rand()%10000;
- cout<<“a=”<<a<<” , b=”<<b<<” , N =”<<N<<” , modexp_re = “<<modexp_re(a,b,N)<<endl;
- cout<<“a=”<<a<<” , b=”<<b<<” , N =”<<N<<” , modexp_nonre = “<<modexp_nonre(a,b,N)<<endl;
- i++;
- }
- system(“pause”) ;
- return 0 ;
- }
- // function modexp in recursion
- int modexp_re(int x,int y,int N)
- {
- // exception
- if(N <= 0)
- {
- cout<<“exception of function modexp_re input N “<<endl;
- return -1;
- }
- // exit
- if(y == 0)
- return 1;
- else
- {
- int z = modexp_re(x,y/2,N);
- if(y%2 == 0)
- return ( (z%N) * (z%N) ) % N;
- else return ((((x%N) * (z%N)) %N) *(z%N) )% N;
- }
- }
- // function modexp without recursion
- int modexp_nonre(int x,int y,int N)
- {
- // exception
- if(N <= 0)
- {
- cout<<“exception of function modexp_re input N “<<endl;
- return -1;
- }
- // exit
- if(y == 0)
- return 1;
- else
- {
- int result,z;
- stack<int> * s = new stack<int>;
- while(y >= 1)
- {
- s->push(y);
- y = y/2;
- }
- result = x % N;
- while(s->size()>1)
- {
- z = s->top();
- s->pop();
- result = ( (result%N) * (result%N) )%N;
- if(s->empty())
- break;
- else if(z*2 != s->top())
- {
- result = (result * (x%N) )%N;
- }
- }
- return result;
- }
- }