杭电ACM1395——2^x mod n = 1~~水题

来源:互联网 发布:制作软件的工具 编辑:程序博客网 时间:2024/04/28 15:03

题目的意思很清楚。求最小的x使2^x mod n = 1。n是输入的。

直接暴力过,用快速幂运算。一开始忘记了n = 1的情况,导致TLE。

下面的是AC的代码:

#include <iostream>using namespace std;int main(){int n, x, i;while(cin >> n){if(n % 2 == 0 || n == 1)          //n为偶数或者1的时候,直接输出下面的,因为不存在{cout << "2^? mod " << n << " = 1" << endl;continue;}for(i = 1; ; i++)                 //快速幂运算求解{x = 2;int ans = 1;int m = i;while(m > 0){if(m & 1)ans = ans * x % n;x = x * x % n;m >>= 1;}if(ans == 1)             //找到,退出{cout << "2^" << i <<" mod " << n << " = 1" << endl;break;}}}return 0;}


0 0