I need to iterate over all integers that are:
- Composite
- Squarefree
- Smaller than a limit $L$
And see for each one if it has a certain property (in addition to these 3). Then I need to sum all such integers with this property. The following code does exactly that:
public static void main(String[] args)
{
long L=(long) Math.pow(10,12);
long [] primes = eratosthenes(L/2);
long sigma=0;
for (int i=0;i<primes.length-1;i++)
sigma+=squareFreeCompositesGenerator(L,primes[i],i+1,primes);
System.out.println(sigma);
}
public static long squareFreeCompositesGenerator(long L, long prod, int position, long [] primes)
{
long sum=0;
for (int i=position;i<primes.length&&prod*primes[i]<=L;i++)
{
if (property(prod*primes[i]))
sum+=prod*primes[i];
sum+=squareFreeCompositesGenerator(limit,prod*primes[i],i+1,primes);
}
return sum;
}
The idea behind this, is that rather than checking all numbers up to $L$ if they're squarefree, I can rather simply create/generate them, which is considerably faster compared to iterating through all numbers up to $L$ and factor and check each one. In this code, a call for eratosthenes(n) returns a sieve of all primes up to $n$. The method squareFreeCompositesGenerator then "creates" all squarefree composites smaller than $L$, and checks if they have the property through the property method. Through recursion, it keeps multiplying the primes without repetition and runs through all possible combinations. The "Achilles heel" of this algorithm though, is in the very beginning, where I require all primes $p \leqslant \frac L2$. This is due to the fact that the largest possible such integer can be of the form $2 \cdot p$ where $p$ is the largest prime up to $ \frac L2$. The program runs swiftly even for $L=10^9$ but for $L$ as big as $10^{12}$, I can't create and store all those primes in reasonable time, and even if I could store them, it would still take a long time.
It is important to note I don't need to sum all squarefree composites $\lt L$, or count how many there are, but rather iterate through all of them and check if they have a certain property.
Is there any way to adjust the code so that it only requires primes up to $\sqrt n$? Or is there perhaps another approach to iterate through all squarefree composites $\lt L$ with a sublinear time complexity?
Try this
on https://octave-online.net/