You can sometimes find the solution by trying with the first values and see what happens :
public static void main(String[] args) {
for(int i = 0; i< 100; i++) {
System.out.println("" + i +" : " + (int)Math.pow(2, i) % 23);
}
}
Here is the result :
0 : 1
1 : 2
2 : 4
3 : 8
4 : 16
5 : 9
6 : 18
7 : 13
8 : 3
9 : 6
10 : 12
11 : 1
12 : 2
13 : 4
14 : 8
15 : 16
16 : 9
17 : 18
18 : 13
19 : 3
20 : 6
21 : 12
22 : 1
23 : 2
24 : 4
25 : 8
26 : 16
27 : 9
28 : 18
29 : 13
30 : 3
31 : 5
32 : 5
33 : 5
I cut the output but for each value after 33, the result will be 5
, because of some overflows.
But you can see that there is a loop in the results : 1 2 4 8 16 9 18 13 3 6 12
.
This is explained because of this mathematical relationship :
(2^(n+1)) mod 23 = ((2 ^ n) mod 23) * 2 mod 23
(in english, multiply the previous result by 2 and apply a mod 23 if necessary)
So
- when
n = 10
, the result is 12
- when
n = 11
, the result is 12 * 2 mod 23 = 24 mod 23 = 1 and there you go for a new cycle 1, 2, 4 etc
Hence the answer is that eihter you find the corresponding value in the first 10 tries or you will never find it.
Trying to find a value of 5
or 7
will end in an infinite loop.