Question

Trying to print the prime factors of a number using Erathosthenes sieve instead of finding the factors and then checking whether each factor is a prime number.

 #include<stdio.h>
 #include<math.h>

void primeFactors(int num)
{
    int factors[100];

    int i,j=0,u,k=0,l;
    u=sqrt(num);

    for(i=0;i<100;i++)
        factors[i]=1;

    for(i=2;i<=u;i++)
    {
        if(factors[i]==0)
            continue;

        if(num%i==0)
        {
            factors[j]=i;
            l=factors[j];
            k=2*factors[j];
            j++;

            while(k<=u)
            {
                if(factors[k]==0)
                    continue;
                factors[k]=0;
                k+=l;
            }
        }
    }

    for(i=2;i<=u;i++)
        if(factors[i]!=1)
            printf("%d\n",factors[i]);

}

int main()
{
    int n=797;
    primeFactors(n);
    return 0;
}

On running it on Xcode it neither shows any error nor prints a single thing. I can't figure out the issue . Why isn't this printing? Thanks.

Was it helpful?

Solution

This part:

while(k<=u)
{
    if(factors[k]==0)
        continue;

looks a lot like an infinite loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top