0
967views
Write a program to display prime numbers between 1 to 1000
1 Answer
1
4views

Normal Approach :

#include<stdio.h>

int main()
{
    for ( int i = 1; i <= 1000; i++ ) {
        bool prime = 1;
        for ( int j = 2; j < i; j++ ) {
            if ( i % j == 0 ) {
                prime = 0;
                break;
            }
        }

        if ( prime ) printf ( "%d\n", i );
    }


    return 0;
}

Using Sieve

#include<stdio.h>

const int MX = 1e3+123;
bool is_prime[MX];
int prime[MX];

void primeGen ( int n )
{
    for ( int i = 3; i <= n; i += 2 ) is_prime[i] = 1;

    int sq = sqrt ( n );
    for ( int i = 3; i <= sq; i += 2 ) {
        if ( is_prime[i] == 1 ) {
            for ( int j = i*i; j <= n; j += ( i + i ) ) {
                is_prime[j] = 0;
            }
        }
    }

    is_prime[2] = 1;
    prime.push_back (2);

    for ( int i = 3; i <= n; i += 2 ) {
        if ( is_prime[i] == 1 ) prime.push_back ( i );
    }
}

int main()
{
    primeGen(1000);
    for ( auto u : prime ) {
        cout << u << endl;
    }


    return 0;
}
Please log in to add an answer.