Find numbers in a range which are coprime with a number
Answers
P.S SAVE PENGUINS
Step-by-step explanation:
have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
Questions Jobs Tags Users Badges Ask
Up vote
2
Down vote
How to count co-prime to n in a range [1,x] where x can be different from n?
c++ algorithm primes
I want to count co-primes of n in a range [1,x]. I have tried using euler phi function but it gives for [1,n].Can anyone suggest a modification to euler phi or any other approach to do this? I have used phi(n) = n* product of (1-(1/p)) where p is a prime factor of n.
share improve this question follow
asked
Jun 15 '13 at 6:12
X-men
33●11 silver badge●33 bronze badges edited
Jan 7 '14 at 13:51
Benjamin
29.6k●3838 gold badges●153153 silver badges●276276 bronze badges
How large are n and x? – Peter de Rivaz Jun 15 '13 at 7:59
You can use a sieve. See programmingpraxis.com/2012/07/10/sieving-for-totients for the solution to a similar problem. – user448810 Jun 15 '13 at 11:31
add a comment
1 Answer
order by
votes
Up vote
2
Down vote
Accepted
You can use Inclusion-Exclusion Principle
Find the unique prime factors of N (they cannot be more than 10-12, Considering N and X <=10^10).
Now you can find the number of numbers <=x and divisible by 'y' just by dividing. Try all combination of factors of n for y (you will get only 2^10 (1024) in worst case). Use Inclusion Exclusion now to find the co-primes of n less than x.
The idea is that if a number is not co-prime to n, then it will have at least one prime factor common with n.
For our example here lets consider X=35 and N=30
First find the unique prime factor of the number. (their number must not be greater than 10-12). Unique Prime factor of N ={2,3,5}.
Find the product of each factor PAIR. {2x3, 2x5, 3x5 or 6, 10, 15}.