Home > Software design >  can someone explain this equation to me from the c program about generating prime number till 100
can someone explain this equation to me from the c program about generating prime number till 100

Time:12-13

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
    int p;
    int i;
    int j;

    int primes[50] = {0};
    int primeIndex = 2;

    bool isPrime;

    // hardcode prime numbers
    primes[0] = 2;
    primes[1] = 3;

    for(p = 5; p <= 100; p = p   2)
    {
        isPrime = true;


        for (i = 1; isPrime && p / primes[i] >= primes[i];   i)
            if (p % primes[i] == 0)
                isPrime = false;



        if (isPrime == true)
        {
            primes[primeIndex] = p;
              primeIndex;
        }
    }

    for ( i = 0;  i < primeIndex;    i )
         printf ("%i  ", primes[i]);

    printf("\n");
    return 0;
}

explain ths eqution from above program

        for (i = 1; isPrime && p / primes[i] >= primes[i];   i)
            if (p % primes[i] == 0)
                isPrime = false;

the code works fine it about generating prime number till 100 and storing in arry and then displaying it but I didnt understand it's logic ples explain it to me

CodePudding user response:

It checks if the number has been found not prime until now. Then it checks if the number is bigger than the square root of the next prime to check. If the number can be divided by that prime, then it isn't prime. If not, it will check the next one and so on. After the for loop, if isPrime variable is still true, then the number is prime and will be added to the array.

  • Related