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 :
- // n range of numbers from 1 to n
- // p array of primes for divisibility check
- long f(long n, long [] p)
- {
- if(p.Length==0)
- return 0;
- long [] q = new long[p.Length-1];
- Array.Copy(p,1,q,0,p.Length-1);
- long r = (n/p[0])- (f(n/p[0],q)) + (f(n,q));
- 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


Dharmraj ThakurRank #577 · 4.2K reputationPosted Dec 31, 2017, 9:01 PM EST
Dharmraj ThakurRank #577 · 4.2K reputationPosted Jan 3, 2018, 2:30 AM EST
Arun PottiRank #196 · 12.2K reputationPosted Oct 31, 2026, 9:23 PM EDT
Your recursion is essentially applying the inclusion-exclusion principle, but it creates a new array with
Array.Copyon every recursive call and repeats calculations. You can make it faster by iterating over combinations of the primes and avoiding array allocations.static long Count(long n, long[] primes)
{
long result = 0;
int combinations = 1 << primes.Length;
for (int mask = 1; mask < combinations; mask++)
{
long product = 1;
int count = 0;
bool valid = true;
for (int i = 0; i < primes.Length; i++)
{
if ((mask & (1 << i)) == 0)
continue;
// Avoid overflow and combinations that cannot divide
// any number <= n.
if (product > n / primes[i])
{
valid = false;
break;
}
product *= primes[i];
count++;
}
if (!valid)
continue;
long divisible = n / product;
if ((count & 1) == 1)
result += divisible;
else
result -= divisible;
}
return result;
}
Željko PerićRank #644 · 3.7K reputationPosted Jan 3, 2018, 2:14 AM EST
Željko PerićRank #644 · 3.7K reputationPosted Oct 31, 2026, 4:29 PM EDT
After 8 years here is improved version of upper solution that gives currently best performance speed/memory:
using System; using System.Collections.Generic; namespace CountDivisibleNumbers { /// /// Provides an optimized memoized version of the original recursive divisibility algorithm, /// using the Inclusion-Exclusion Principle with caching to eliminate redundant calculations and memory allocations. /// public static class MemoizedOriginalDivisibilityCounter { private static readonly Dictionary _memo = new(); /// /// Calculates the count of numbers in the range [m, n] that are divisible /// by any of the numbers in the test array p, utilizing memoization. /// /// The lower bound of the range (inclusive). /// The upper bound of the range (inclusive). /// An array of test numbers for the divisibility check. /// The count of divisible numbers in the specified range [m, n]. /// /// IMPORTANT: No duplicates are allowed, and no mutually divisible numbers are allowed /// (e.g., 4 and 2, or 35 and 5). The input array p must be filtered beforehand /// to ensure correct mathematical results and optimal recursive performance. /// public static long CalculateRange(long m, long n, long[] p) { _memo.Clear(); long countN = Compute(n, p, 0); _memo.Clear(); long countM1 = Compute(m - 1, p, 0); return countN - countM1; } /// /// Core recursive function with memoization implementing the Inclusion-Exclusion Principle /// to count how many numbers from 1 to n are divisible by any number in array p. /// /// The upper limit of the number range [1, n]. /// The array of test divisors. /// The current index in the test array. /// The count of divisible numbers up to n starting from the given index. /// /// IMPORTANT: No duplicates are allowed, and no mutually divisible numbers are allowed /// (e.g., 4 and 2, or 35 and 5). The input array p must be filtered beforehand /// to ensure correct mathematical results and optimal recursive performance. /// private static long Compute(long n, long[] p, int index) { if (index >= p.Length) return 0; var key = (n, index); if (_memo.TryGetValue(key, out long cachedResult)) { return cachedResult; } long countDivisible = n / p[index]; long term1 = Compute(n / p[index], p, index + 1); long term2 = Compute(n, p, index + 1); long r = countDivisible - term1 + term2; _memo[key] = r; return r; } } }Benchmark Environment & System Specs:
BenchmarkDotNet Version: v0.15.8
Operating System: Windows 11 (10.0.26300.9711)
Processor (CPU): 13th Gen Intel Core i7-1360P 2.20GHz, 1 CPU, 16 logical and 12 physical cores
SDK / Runtime: .NET SDK 10.0.403 (RyuJIT x86-64-v3)
Conclusion:
The evolution from a naive linear scan to an advanced recursive algorithm based on the Inclusion-Exclusion Principle demonstrates how number theory combined with modern .NET optimization techniques (such as dictionary-based memoization) can solve complex computational tasks within microseconds. Benchmark results clearly confirm that the memoized version incurs zero managed memory allocations (0 B) and vastly outperforms the original recursion, ensuring robust, lightning-fast performance even with colossal ranges up to
long.MaxValue.All the best,
Željko Peric
Željko PerićRank #644 · 3.7K reputationPosted Oct 31, 2026, 5:06 PM EDT
New examples of more optimized code:
Benchmark Environment & System Specs:
BenchmarkDotNet Version: v0.15.8
Operating System: Windows 11 (10.0.26300.9818)
Processor (CPU): 13th Gen Intel Core i7-1360P 2.20GHz, 1 CPU, 16 logical and 12 physical cores
SDK / Runtime: .NET SDK 10.0.403 (RyuJIT x86-64-v3)
All the best,
Željko Perić
Željko PerićRank #644 · 3.7K reputationPosted Oct 31, 2026, 5:28 PM EDT
For everyone who wants to download the complete source code, explore advanced optimizations (including
CollectionsMarshalandInt128versions), the project is available at the following link:periczeljkosmederevo/CountDivisibleNumbers
High-performance C# implementation and benchmarks for counting numbers in a range divisible by given primes using the Inclusion-Exclusion Principle.