Home > Software design >  Prime number loop logic
Prime number loop logic

Time:11-15

I wanted to ask you somthing that i cant understand why it works. i need to make a code that you input some number and it gives you all the prime numbers until you get to that num.

now i have this code that does the trick. like every number that is not prime it goes to the next n and checks it but i dont understand this if like it gets 4 and then turns it to 5 the j wont go to 3? and then you start checking 5/3 but you miss the division by 2 and so on like i dont get it does it resets the j to 2 every time that i edd i 1?

also if i give it like 10 it prints 11 and i dont want it to pass the original number how do i do that.

int num;

printf("please enter num ");
scanf_s("%d", &num);
int i, j;
for (i = 2; i < num; i  )
{
    for (j = 2; j < i; j  )
    {

        printf("j=%d ", j);

        if (i % j == 0)
            i  = 1;


    }
    printf("%d ", i);


}

CodePudding user response:

  1. "code that does the trick" simply fails for various num. Going to the next i (if (i % j == 0) i = 1;) fails as code needs to test against smaller j again with the new i. Recommend forming a helper function.
for (i = 2; i < num; i  ) {
  if (isprime(i)) printf("%d ", i);
}
  1. Sieve of Eratosthenes is a much better approach. @NeilB

CodePudding user response:

now i have this code that does the trick

No, the algorithm is wrong.

This

int num;
printf("please enter num ");
scanf("%d", &num);
int i, j;
for (i = 2; i < num; i  )
{
    for (j = 2; j < i; j  )
    {    
        // commented out   printf("j=%d ", j);

        if (i % j == 0)
            i  = 1;
    }
    printf("%d ", i);
}

with input value 30 will give the output

2 3 5 7 11 13 17 19 23 27 29

but 27 is not a prime

A few other values that the algo handles incorrect: 35, 87, 95

  • Related