Alternate Primes till N - GeeksforGeeks

25 Oct, 2021
We have to print alternate prime numbers till N.Examples:  
Input : N = 10
Output : 2 5 

Input : N = 15
Output : 2 5 11 
 
Naive Approach:We can just simply iterate over N and check whether the number is prime or not and print the alternate number just by keeping a simple altering flag variable. 
C++
Java
Python3
C#
PHP
Javascript
/* C++ program to print allprimes smaller than orequal to n using Naive approach.*/#include<bits/stdc++.h>using namespace std; /* Function for checkingnumber is prime or not */int prime(int num){    int i, flag = 0;    for(i = 2; i<= num / 2; i++)    {        if(num % i == 0)        {            flag = 1;            break;        }    }         // if flag = 0 then number    // is prime and return 1    // otherwise return 0    if(flag == 0)        return 1;    else        return 0;} // Function for printing// alternate prime numbervoid print_alternate_prime(int n){    // counter is initialize with 0    int counter = 0;     // looping through 2 to n-1    for(int num = 2; num < n; num++)    {        // function calling along        // with if condition        if (prime(num) == 1)        {            // if counter is multiple of 2            // then only print prime number            if (counter % 2 == 0)                cout << num << " ";                             counter ++;        }    }} // Driver codeint main(){    int n = 15;    cout << "Following are the alternate prime"         << " number smaller than or equal to "         << n << endl;              // Function calling    print_alternate_prime(n);}         // This code is contributed// by ChitraNayal
// Java program to print all// primes smaller than or// equal to n using Naive approach.class GFG{     /* Function for checkingnumber is prime or not */static int prime(int num){int i, flag = 0;for(i = 2; i<= num / 2; i++){    if(num % i == 0)    {        flag = 1;        break;    }} // if flag = 0 then number is prime// and return 1 otherwise return 0if(flag == 0)    return 1;else    return 0;} // Function for printing// alternate prime numberstatic void print_alternate_prime(int n){// counter is initialize with 0int counter = 0; // looping through 2 to n-1for(int num = 2; num < n; num++){    // function calling along    // with if condition    if (prime(num) == 1)    {        // if counter is multiple of 2        // then only print prime number        if (counter % 2 == 0)            System.out.print(num + " ");                         counter ++;    }}} // Driver codepublic static void main(String[] args){    int n = 15;    System.out.println("Following are the alternate " +                         "prime number smaller than " +                                   "or equal to " + n);     // Function calling    print_alternate_prime(n);}} // This code is contributed// by ChitraNayal
# Python3 program to print all# primes smaller than or# equal to n using Naive approach. # Function for checking number# is prime or notdef prime(num) :    flag = 0    for i in range(2,num // 2 + 1) :        if num % i == 0 :            flag = 1            break    # if flag = 0 then number is prime    # and return 1 otherwise return 0    if flag == 0 :        return 1    else :        return 0 # Function for printing alternate prime numberdef print_alternate_prime(n):         # counter is initialize with 0    counter = 0     # looping through 2 to n-1    for num in range(2,n) :                 # function calling along with if condition        if prime(num) == 1 :                         # if counter is multiple of 2 then            # only print prime number            if counter % 2 == 0 :                print(num,end =" ")                             counter += 1 # Driver codeif __name__ == "__main__":    n = 15    print("Following are the alternate prime"          +"number smaller than or equal to",n)                # Function calling    print_alternate_prime(n)        
// C# program to print all// primes smaller than or// equal to n using Naive approach.using System;class GFG{/* Function for checkingnumber is prime or not */static int prime(int num){int i, flag = 0;for(i = 2; i <= num / 2; i++){    if(num % i == 0)    {        flag = 1;        break;    }} // if flag = 0 then number is prime// and return 1 otherwise return 0if(flag == 0)    return 1;else    return 0;} // Function for printing// alternate prime numberstatic void print_alternate_prime(int n){// counter is initialize with 0int counter = 0; // looping through 2 to n-1for(int num = 2; num < n; num++){    // function calling along    // with if condition    if (prime(num) == 1)    {        // if counter is multiple of 2        // then only print prime number        if (counter % 2 == 0)            Console.Write(num + " ");                         counter ++;    }}} // Driver codepublic static void Main(){    int n = 15;    Console.Write("Following are the alternate " +                    "prime number smaller than " +                       "or equal to " + n + "\n");     // Function calling    print_alternate_prime(n);}} // This code is contributed// by ChitraNayal
<?php// PHP program to print all// primes smaller than or// equal to n using Naive approach. // Function for checking number// is prime or notfunction prime($num){    $flag = 0;    for($i = 2; $i <= $num / 2; $i++)    {        if ($num % $i == 0)        {            $flag = 1;            break;        }    }         // if flag = 0 then number is prime    // and return 1 otherwise return 0    if ($flag == 0)        return 1;    else        return 0;} // Function for printing// alternate prime numberfunction print_alternate_prime($n){         // counter is initialize with 0    $counter = 0;     // looping through 2 to n-1    for($num = 2; $num < $n; $num++)    {        // function calling along        // with if condition        if(prime($num) == 1)        {            // if counter is multiple of 2            // then only print prime number            if ($counter % 2 == 0 )                echo $num . " ";                             $counter += 1;        }    }} // Driver code$n = 15;echo "Following are the alternate prime ".      "number smaller than or equal to " .                                $n . "\n";// Function callingprint_alternate_prime($n); // This code is contributed// by ChitraNayal?>
<script>// javascript program to print all// primes smaller than or// equal to n using Naive approach.   /*     * Function for checking number is prime or not     */    function prime(num) {        var i, flag = 0;        for (i = 2; i <= num / 2; i++) {            if (num % i == 0) {                flag = 1;                break;            }        }         // if flag = 0 then number is prime        // and return 1 otherwise return 0        if (flag == 0)            return 1;        else            return 0;    }     // Function for printing    // alternate prime number    function print_alternate_prime(n)    {             // counter is initialize with 0        var counter = 0;         // looping through 2 to n-1        for (num = 2; num < n; num++)        {                     // function calling along            // with if condition            if (prime(num) == 1)            {                             // if counter is multiple of 2                // then only print prime number                if (counter % 2 == 0)                    document.write(num + " ");                 counter++;            }        }    }     // Driver code    var n = 15;    document.write("Following are the alternate " + "prime number smaller than " + "or equal to " + n+"<br/>");     // Function calling    print_alternate_prime(n); // This code is contributed by Rajput-Ji</script>
Following are the alternate prime numbers smaller  than or equal to 15
2 5 11
 
Time Complexity: O(N * )Efficient approach: Using Sieve of Eratosthenes we can just print all the alternate true values in the sieve. 
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to print all primes smaller than or// equal to n using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n){    // Create a boolean array "prime[0..n]" and initialize    // all entries it as true. A value in prime[i] will    // finally be false if i is Not a prime, else true.    bool prime[n + 1];    memset(prime, true, sizeof(prime));     for (int p = 2; p * p <= n; p++) {         // If prime[p] is not changed, then        // it is a prime        if (prime[p] == true) {             // Update all multiples of p            for (int i = p * 2; i <= n; i += p)                prime[i] = false;        }    }     // Print all prime numbers    bool flag = true;    for (int p = 2; p <= n; p++) {        if (prime[p]) {            if (flag) {                cout << p << " ";                flag = false;            }            else {                 // for next prime to get printed                flag = true;            }        }    }} // Driver Program to test above functionint main(){    int n = 15;    cout << "Following are the alternate"         << " prime numbers smaller "         << " than or equal to " << n << endl;    SieveOfEratosthenes(n);    return 0;}
// Java program to print all primes// smaller than or equal to n using// Sieve of Eratosthenesclass GFG{static void SieveOfEratosthenes(int n){// Create a boolean array "prime[0..n]"// and initialize all entries it as// true. A value in prime[i] will// finally be false if i is Not a// prime, else true.boolean []prime = new boolean[n + 1];for(int i = 0; i < prime.length; i++)    prime[i] = true; for (int p = 2; p * p <= n; p++){     // If prime[p] is not changed,    // then it is a prime    if (prime[p] == true)    {         // Update all multiples of p        for (int i = p * 2;                 i <= n; i += p)            prime[i] = false;    }} // Print all prime numbersboolean flag = true;for (int p = 2; p <= n; p++){    if (prime[p])    {        if (flag)        {            System.out.print(p + " ");            flag = false;        }        else        {             // for next prime            // to get printed            flag = true;        }    }}} // Driver Codepublic static void main(String[] args){    int n = 15;    System.out.println("Following are the alternate" +                           " prime numbers smaller " +                            "than or equal to " + n );    SieveOfEratosthenes(n);}} // This code is contributed// by ChitraNayal
# Python 3 program to print all# equal to n using Sieve of Eratosthenes def SieveOfEratosthenes(n):     # Create a boolean array    # "prime[0..n]" and initialize    # all entries it as true. A value    # in prime[i] will finally be false    # if i is Not a prime, else true.    prime = [None] * (n + 1)    for i in range(len(prime)):        prime[i] = True     p = 2    while p * p <= n:         # If prime[p] is not changed,        # then it is a prime        if (prime[p] == True):             # Update all multiples of p            for i in range(p * 2, n + 1, p):                prime[i] = False                         p += 1     # Print all prime numbers    flag = True    for p in range(2, n + 1):        if (prime[p]):            if (flag):                print(str(p), end = " ")                flag = False                         else:                 # for next prime to get printed                flag = True # Driver Codeif __name__ == "__main__":    n = 15    print("Following are the alternate" +              " prime numbers smaller " +            "than or equal to " + str(n))    SieveOfEratosthenes(n) # This code is contributed# by ChitraNayal
// C# program to print all primes// smaller than or equal to n using// Sieve of Eratosthenesusing System; class GFG{static void SieveOfEratosthenes(int n){     // Create a bool array "prime[0..n]"// and initialize all entries it as// true. A value in prime[i] will// finally be false if i is Not a// prime, else true.bool[] prime = new bool[n + 1];for(int i = 0; i < prime.Length; i++)    prime[i] = true; for (int p = 2; p * p <= n; p++){     // If prime[p] is not changed,    // then it is a prime    if (prime[p] == true)    {         // Update all multiples of p        for (int i = p * 2;                 i <= n; i += p)            prime[i] = false;    }} // Print all prime numbersbool flag = true;for (int p = 2; p <= n; p++){    if (prime[p])    {        if (flag)        {            Console.Write(p + " ");            flag = false;        }        else        {             // for next prime to            // get printed            flag = true;        }    }}} // Driver Codepublic static void Main(){    int n = 15;    Console.Write("Following are the alternate" +                      " prime numbers smaller " +                 "than or equal to " + n + "\n");    SieveOfEratosthenes(n);}} // This code is contributed// by ChitraNayal
<?php// PHP program to print all// primes smaller than or// equal to n using Sieve// of Eratosthenesfunction SieveOfEratosthenes($n){    // Create a boolean array    // "prime[0..n]" and initialize    // all entries it as true. A value    // in prime[i] will finally be    // false if i is Not a prime, else true.    $prime = array();    for( $i = 0; $i <= $n; $i++)        $prime[$i] = true;     for ($p = 2; $p * $p <= $n; $p++)    {         // If prime[p] is not changed,        // then it is a prime        if ($prime[$p] == true)        {             // Update all multiples of p            for ($i = $p * 2;                 $i <= $n; $i += $p)                $prime[$i] = false;        }    }     // Print all prime numbers    $flag = true;    for ($p = 2; $p <= $n; $p++)    {        if ($prime[$p])        {            if ($flag)            {                echo $p . " ";                $flag = false;            }            else            {                 // for next prime to                // get printed                $flag = true;            }        }    }} // Driver Code$n = 15;echo "Following are the alternate".         " prime numbers smaller ".   "than or equal to " . $n . "\n";SieveOfEratosthenes($n); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to print all primes// smaller than or equal to n using// Sieve of Eratosthenes function SieveOfEratosthenes(n){    // Create a boolean array "prime[0..n]"// and initialize all entries it as// true. A value in prime[i] will// finally be false if i is Not a// prime, else true.let prime = new Array(n + 1);for(let i = 0; i < prime.length; i++)    prime[i] = true;  for (let p = 2; p * p <= n; p++){      // If prime[p] is not changed,    // then it is a prime    if (prime[p] == true)    {          // Update all multiples of p        for (let i = p * 2;                 i <= n; i += p)            prime[i] = false;    }}  // Print all prime numberslet flag = true;for (let p = 2; p <= n; p++){    if (prime[p])    {        if (flag)        {            document.write(p + " ");            flag = false;        }        else        {              // for next prime            // to get printed            flag = true;        }    }}} // Driver Codelet  n = 15;document.write("Following are the alternate" +                           " prime numbers smaller " +                            "than or equal to " + n +"<br>");     SieveOfEratosthenes(n);// This code is contributed by avanitrachhadiya2155</script>
Following are the alternate prime numbers smaller  than or equal to 15
2 5 11
 
Time complexity: O(*log(log(N))) for applying sieving and O(N) for traversing the sieve. 
ankthon
ukasp
Rajput-Ji
avanitrachhadiya2155
ankita_saini
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to convert a given number to words
Count ways to reach the n'th stair
Fizz Buzz Implementation
Program to print prime numbers from 1 to N.
Singular Value Decomposition (SVD)
Find first and last digits of a number
Check if a number is Palindrome