Write a program that takes an integer from standard input an
Solution
Hi buddy, I\'ve written 2 programs for you. The first one is the one you asked for and the second one uses sieve method. That is much faster .
Method 1 :
#include <stdio.h>
 #include <math.h>
int isPrime(int n){
     //Finding square root of n
     int e = (int)sqrt((float)n);
     //if n is even, return false
     if(n%2==0){
         return 0;
     }
     //Check whether n is divisible by all the odd numbers till e
     for(int i=3;i<=e;i+=2){
         if(n%i==0){
             return 0;
         }
     }
     return 1;
 }
int main(void) {
         //Prompting and reading an integer
        printf(\"Input a number greater than 2\ \");
        int n;
        scanf(\"%d\",&n);
       
        //If number less than 2, give msg
        if(n<=2){
             printf(\"No prime number is smaller than %d\ \",n);
             return 0;
        }
       
        printf(\"Input : %d ; Output : 2 \",n);
       
        for(int i=3;i<=n;i++){
             if(isPrime(i)==1){
                 printf(\"%d \",i);
             }
        }
        printf(\"\ \");
        return 0;
 }
Input : 20
OUTPUT :
Input a number greater than 2
 Input : 20 ; Output : 2 3 5 7 11 13 17 19
Method 2 :
#include <stdio.h>
int main(void) {
         //Prompting and reading an integer
        printf(\"Input a number greater than 2\ \");
        int n;
        scanf(\"%d\",&n);
       
        //If number less than 2, give msg
        if(n<=2){
             printf(\"No prime number is smaller than %d\ \",n);
             return;
        }
       
        printf(\"Input : %d ; Output : 2 \",n);
       
        //Initialize an array of n intergers and initialize with 1
        int primes[n+1];
        for(int i=0;i<=n;i++){
             primes[i] = 1;
        }
       
        //I\'m using sieve method to fill populate the array
        for(int i=2;i<=n;i++){
             for(int j=2;j*i<=n;j++){
                 //Number i*j can\'t be prime number because both i and j are factors
                 primes[i*j] = 0;
             }
        }
       
        //Print the numbers whose prime[i] is 1. (You can skip even numbers (+=2))
        for(int i=3;i<=n;i+=2){
             if(primes[i]==1){
                 printf(\"%d \",i);
             }
        }
        printf(\"\ \");
        return 0;
 }
Input : 20
OUTPUT :
Input a number greater than 2
 Input : 20 ; Output : 2 3 5 7 11 13 17 19


