Željko Perić

Željko Perić

  • 447
  • 3k
  • 202k

How many numbers 1 - n are divisible by a range of primes

Dec 30 2017 4:15 PM
Hello, there was interesting simple math problem I have recently solved :
- How many positive integers in a range 1 to n are divisible by at least one of given primes ?
 
Here is the recursive function that solves the problem :
 
  1. // n range of numbers from 1 to n  
  2. // p array of primes for divisibility check  
  3. long f(long n, long [] p)  
  4. {  
  5.     if(p.Length==0)  
  6.         return 0;  
  7.               
  8.     long [] q = new long[p.Length-1];  
  9.               
  10.     Array.Copy(p,1,q,0,p.Length-1);  
  11.               
  12.     long r = (n/p[0])- (f(n/p[0],q)) + (f(n,q));  
  13.               
  14.     return r;    

 My question is :
- Is it possible to write this function in C# differently so that its execution becomes faster ?
 
All the best,
Željko Peric

Answers (3)