当前位置:编程学习 > C/C++ >>

hdu1395-2^x mod n = 1

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


 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,