Recently I gave Amazon coding test, in which i got the following question —
Given n, find all numbers from 1 to n, which are coprime with n. ex. Input: n = 5 Output: 4 Explanation — The numbers coprime with n = 5 are (1,5), (2,5), (3,5), (4,5)
Input: n = 10 Output: 4 Explanation — (1,10), (3,10), (7,10), (9,10)
Constraints 1 <= n <= 10^9.
I wrote a brute force solution, where i took each numebr from 1 to n and tried to find its gcd with n. Which apparently gave a TLE on most of the test cases.
Can anyone kindly guide me how to solve this problem ?