hdu1395-2^x mod n = 1

时间:2023-03-10 05:46:23
hdu1395-2^x mod n = 1

http://acm.hdu.edu.cn/showproblem.php?pid=1395

原理为 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 ;
}