Question link:
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1395
You must read all the code.
This is a mathematical question. I have no idea. I only know that X cannot be found when n = 1 | n % 2 = 0, otherwise, it is unknown that X cannot be found if n exists,
In addition, if you do not know where to locate the brute force search task and submit the task, the task times out and reads others' blogs: if a and n are mutually qualitative and a <n, a ^ X % n = 1. Therefore, in this question, a is 2.
So as long as! = 1 & A % 2! = 0, then there must be X,
# Include <stdio. h>
Int main (void)
{
Int S, N;
While (scanf ("% d", & n) = 1)
{
If (N % 2 = 0 | n = 1)
{
Printf ("2 ^? MoD % d = 1 \ n ", N );
Continue;
}
Int m = 2;
S = 1;
Int K = 0;
For (;;)
{
S = S * m;
K ++;
If (S = n + 1)
{
Printf ("2 ^ % d mod % d = 1 \ n", k, n );
Break;
}
If (S> n + 1)
S = S % N; // prevents excessive data Overflow
}
}
Return 0;
}
Another solution
# Include <stdio. h>
Int main (void)
{
Int S, N, I;
Int m;
While (scanf ("% d", & n) = 1)
{
If (n = 1 | n % 2 = 0)
{
Printf ("2 ^? MoD % d = 1 \ n ", N );
Continue;
}
S = 1;
M = 2;
For (I = 1; I <= N; I ++)
{
S = S * m;
If (S % N = 1)
Break;
S = S % N; // prevent overflow;
}
If (I <= N)
Printf ("2 ^ % d mod % d = 1 \ n", I, n );
Else
Printf ("2 ^? MoD % d = 1 \ n ", N );
}
Return 0;
}
Explanation
Q &
Why can I execute a maximum of n times? Sorry, I cannot respond until ^_^.
2 ^ K % N only has n different results
Then the loop starts.
So you only need to try n times at most. If there is a solution, there will be a solution within n times. If there is no solution within n times, there will be no solution for further interviews.
Second modification
# Include <stdio. h>
Int main (void)
{
Int S, N, I;
Int m;
While (scanf ("% d", & n) = 1)
{
If (n = 1 | n % 2 = 0)
{
Printf ("2 ^? MoD % d = 1 \ n ", N );
Continue;
}
S = 1;
M = 2;
For (I = 1; I <= N; I ++)
{
S = S * m;
If (S % N = 1)
Break;
S = S % N;
}
If (I <= N)
Printf ("2 ^ % d mod % d = 1 \ n", I, n );
// Else
// Printf ("2 ^? MoD % d = 1 \ n ", N );
}
Return 0;
}
It can also be explained through the first method of (AC;
All of the above are for others. After all, others are for others, and only their own will be more profound.
Wa time limit exceeded
# Include <stdio. h>
# Include <math. h>
Int main (void)
{
Int S, N, I;
Int m;
While (scanf ("% d", & n) = 1)
{
If (n = 1 | n % 2 = 0)
{
Printf ("2 ^? MoD % d = 1 \ n ", N );
Continue;
}
S = 1;
M = 2;
For (I = 1; I <= N; I ++)
{
S = (INT) (POW (2, I ));
If (S % N = 1)
Break;
S = S % N;
}
If (I <= N)
Printf ("2 ^ % d mod % d = 1 \ n", I, n );
}
Return 0;
}
Why is time limit exceeded, mainly S = (INT) (POW (2, I); two aspects (1) force conversion time consumed, and (2) Pow function time consumed, this causes time limit exceeded.
HDU-1395-2 ^ x mod n = 1 (mathematical problem (secondary error ))