'Given N, find the smallest number A that A^A divisible by N
This problem describes that :
Given N, find the smallest number A that A^A divisible by N. (N<=1.000.000.000)
E.g: N=9 , output A=3 (3^3 mod 9=0) ; given N=6 output A=6 (6^6 mod 6=0).
I calculate from 1 until I find number appropriate, but during I calculate variable (A^A) then data overflow. How can I find number A faster and no data overflow?
Solution 1:[1]
- The prime factors of
Ashould be the same as the prime factors ofN. Having less factors meansA^A % N !=0, having more factors is pointless since we're looking for the smallestA. - Let
Nhave prime factorization2^a * 3^b * 5^c .... The exponent array forNwould beexpo_N = [a,b,c...] - Let
y = product of prime factors of N. The exponent array forywould be[1,1,1...]. The exponent array ofy^ywill beexpo_y = [y,y,y...]. - For
y^yto be divisible byN,expo_y[i] >= expo_N[i] for i in range(length(expo_N)). - Let
x = max(a,b,c...). Now, using the points mentioned above,y >= xto satisfy point #4. Ify>=x, you have the answer. Else, keep on multiplyingyby2whiley < x.
This approach doesn't involve actually exponentiating the numbers, so it would timeout or error out. Factorization of N can be done in O(sqrt(N)), the remaining operations will be done in O(logN) number of prime factors.
Example 1: N = 9
expo_N = [3: 2] (since N = 3^2)y = 3, expo_y = [3: 3]- Since
expo_y[i] >= expo_N[i] for all i, answer isA = y = 3
Example 2: N = 6
expo_N = [2: 1, 3: 1]y = 6, expo_y = [2: 6, 3: 6]- Since
expo_y[i] >= expo_N[i] for all i, answer isA = y = 6
Example 3: N = 384
expo_N = [2: 7, 3: 1]y = 6, expo_y = [2: 6, 3: 6]expo_N[2] = 7, so we multiplyyby2y = 2*y = 12, expo_y = [2: 24, 3: 12]- Now the condition is satisfied, so the answer is
A = y = 12
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
