原理為 a ^ b % n == d ; >>>>>> (( a % n ) ×(a % n ) ×........*(a % n ))%n == d
然後該題當n == 1 或者 n % 2 == 0 時 ,d肯定為 0 ,所以此時無解;
而當n為其他值時,必有1~n - 1的余數存在,因此直接使用求解a ^ b %n ==d 的方法求解即可
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<bitset> #include<iomanip> using namespace std; int main() { int a , b , n ; while( ~scanf( "%d" ,&n ) ) { if( n == 1 || n % 2 == 0 ) { printf( "2^? mod %d = 1\n" , n ); } else { b = 1 ; int temp = 2 ; while( temp != 1 ) { b++ ; temp = ( temp * 2 ) % n ; } printf( "2^%d mod %d = 1\n" , b , n ) ; } } return 0 ; } #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<bitset> #include<iomanip> using namespace std; int main() { int a , b , n ; while( ~scanf( "%d" ,&n ) ) { if( n == 1 || n % 2 == 0 ) { printf( "2^? mod %d = 1\n" , n ); } else { b = 1 ; int temp = 2 ; while( temp != 1 ) { b++ ; temp = ( temp * 2 ) % n ; } printf( "2^%d mod %d = 1\n" , b , n ) ; } } return 0 ; }