Print prime numbers from 1 to n using recursion

Problem statement:- Program to Print prime numbers from 1 to n using recursion.

Data requirement:-

   Input Data:- n

  Output Data:-
i

Program in C

Here is the source code of the C Program to Print prime numbers from 1 to n using recursion.

Code:

#include<stdio.h>
#include<math.h>
int CheckPrime(int i,int num)
{
    if(num==i)
        return 0;
    else
        if(num%i==0)
            return 1;
    else{
        return CheckPrime(i+1,num);
    }
}
int main()
{
    int n,i;
    printf("Enter the N Value:");
    scanf("%d",&n);
    printf("Prime Number Between 1 to n are: ");
   for(i=2;i<=n;i++)
    if(CheckPrime(2,i)==0)
        printf("%d ",i);
}

Input/Output:
Enter the N Value:9
Prime Number Between 1 to n are: 2 3 5 7

Program in C++

Here is the source code of the C++ Program to Print prime numbers from 1 to n using recursion.

Code:

#include<iostream>
#include<cmath>
using namespace std;
int CheckPrime(int i,int num)
{
    if(num==i)
        return 0;
    else
        if(num%i==0)
            return 1;
    else{
        return CheckPrime(i+1,num);
    }
}
int main()
{
    int n,i;
    cout<<"Enter the N Value:";
    cin>>n;
    cout<<"Prime Number Between 1 to n are: ";
   for(i=2;i<=n;i++)
    if(CheckPrime(2,i)==0)
        cout<<i<<" ";
}

Input/Output:
Enter the N Value:15
Prime Number Between 1 to n are: 2 3 5 7 11 13

Program in Java

Here is the source code of the Java Program to Print prime numbers from 1 to n using recursion.

Code:

import java.util.Scanner;
public class PrintPrimeNumber {
static int CheckPrime(int i,int num)
{
    if(num==i)
        return 0;
    else
        if(num%i==0)
            return 1;
    else{
        return CheckPrime(i+1,num);
    }
}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
    int n;
    System.out.print("Enter the N Value:");
    n=cs.nextInt();
    System.out.print("Prime Number Between 1 to n are: ");
    for(int i=2;i<=n;i++)
     if(CheckPrime(2,i)==0)
    System.out.print(i+" ");
    cs.close();
}
}

Input/Output:
Enter the N Value:25
Prime Number Between 1 to n are: 2 3 5 7 11 13 17 19 23 

Program in Python

Here is the source code of the Python Program to Print prime numbers from 1 to n using recursion.

Code:

def CheckPrime(i,num):
    if num==i:
        return 0
    else:
        if(num%i==0):
            return 1
        else:
            return CheckPrime(i+1,num)
n=int(input("Enter your Number:"))
print("Prime Number Between 1 to n are: ")
for i in range(2,n+1):
    if(CheckPrime(2,i)==0):
        print(i,end=" ")

Input/Output:

Post a Comment

0 Comments