2^x modn=1

简介: 2^x modn=1

Give a number n, find the minimum x that satisfies 2^x mod n = 1.

Input One positive integer on each line, the value of n.

Output If the minimum x exists, print a line with 2^x mod n = 1.

Print 2^? mod n = 1 otherwise.

You should replace x and n with specific numbers.

#include <iostream>  
using namespace std;
#include<cmath>
class Fn {
public:
    int X(int n) {
        if (n == 1) return 0;
        if (n % 2 == 0 && n != 2) return -1;
        int x = 1;
        long long a = 2; 
        while (a % n != 1) {
            x++;
           a = (a * 2) % n; 
            if (a== 0) return -1;   
            if (x > n) return -1;  
        }
        return x;
    }
};
int main() {
    Fn b; 
    int n;
    while (cin >> n) { 
        int x = b.X(n); 
        if (x != -1) {
            cout << "2^" << x << " mod " << n << " = 1" << endl;
        }
        else {
           cout << "2^? mod " << n << " = 1" << endl;
        }
    }
    return 0;
}


目录
相关文章
|
7天前
学习使用按位异或 ^
【6月更文挑战第22天】学习使用按位异或 ^。
9 1
|
算法
异或^符号的使用
异或^符号的使用
66 0
|
算法
a^b(快速幂)
题目: 求 a 的 b 次方对 p 取模的值。 输入格式: 三个整数 a,b,p ,在同一行用空格隔开。 输出格式: 输出一个整数,表示a^b mod p的值。
66 0
|
算法 C++
(1+2+...+100)+(1^2+2^2+...+50^2)+(1/1+1/2+...+1/10)
(1+2+...+100)+(1^2+2^2+...+50^2)+(1/1+1/2+...+1/10)
HDOJ 2035 人见人爱A^B
HDOJ 2035 人见人爱A^B
118 0