![]() |
VOOZH | about |
Given a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, ... n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.
Examples:
Input : 10
Output : 1 3 7 9
The set to be generated is {0, 1, .. 9}
By adding 1, single or more times, we
can create all elements from 0 to 9.
Similarly using 3, we can generate all
elements.
30 % 10 = 0, 21 % 10 = 1, 12 % 10 = 2, ...
Same is true for 7 and 9.
Input : 24
Output : 1 5 7 11 13 17 19 23
A simple solution is to run a loop from 1 to n-1 and for every element check if it is generator. To check generator, we keep adding element and we check if we can generate all numbers until remainder starts repeating.
An Efficient solution is based on the fact that a number x is generator if x is relatively prime to n, i.e., gcd(n, x) =1.
Below is the implementation of above approach:
Output :
1 3 7 9
Time Complexity: O(nlogn)
Auxiliary space: O(1)
How does this work?
If we consider all remainders of n consecutive multiples of x, then some remainders would repeat if GCD of x and n is not 1. If some remainders repeat, then x cannot be a generator. Note that after n consecutive multiples, remainders would anyway repeat.
Interesting Observation :
Number of generators of a number n is equal to ?(n) where ? is Euler Totient Function.