ViijayScript: #Program to #check #prime #number in #C #C++ C# #Java #Python #Updated on 2017

Monday 16 October 2017

#Program to #check #prime #number in #C #C++ C# #Java #Python #Updated on 2017

Hello netizens, On this post I am going to tell #Programs to #check #prime #number in #C #C++ #Java C# #Python.

Program in C:

#include <stdio.h>
int check_prime(int);
main()
{
int i, n, result;
printf(“Enter the number of prime numbers required\n”);
scanf(“%d”,&n);
printf(“First %d prime numbers are :\n”, n);
for(i=0; i < n; i++){
result = check_prime(i);
/ if i is prime then it will return 1 /
if ( result == 1 )
printf("%d \n", i);
}
return 0;
}
int check_prime(int a)
{
int c;
/ starting from 2, if no is completely divisible by any no then it is not prime /
for ( c = 2 ; c {
if ( a%c == 0 )
return 0;
}
if ( c == a )
return 1;
}

Program in C++:

#include<iostream.h>
#include<conio.h>
void main ()
{
int num, count = 0 ;
clrscr () ;
cout <> num ;
for (int i = 2 ; i < num ; i ++ )
{
if (num % i == 0 )
{
count ++ ;
break ;
}
}
if (count == 0 )
cout << "Prime number" ;
else
cout << "Not a Prime number" ; getch () ;
}

Program in Java:

import java.util.*;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“Please enter a number: “);
int num = scanner.nextInt(); PrimeNumber primeNum = new PrimeNumber();
if ( primeNum.isPrime(num) ) {
System.out.printf(“\n Result: The number %d is Prime”, num);
} else {
System.out.printf(“\n Result: The number %d is not Prime”, num);
}
} // Method to check whether the number is prime or not
public boolean isPrime(int num) {
if ( num < 2 ) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if ( num % i == 0 ) {
return false;
}
}
return true;
}
}

Program in C#:

using System;
namespace example
{
class prime
{
public static void Main()
{
Console.Write(“Enter a Number: “);
int num;
num=Convert.ToInt32(Console.ReadLine());
int k;
k=0;
for(int i=1;i<=num;i++)
{
if(num%i==0)
{
k++;
}
}
if(k==2)
{
Console.WriteLine("Prime Number");
}
else
{
Console.WriteLine("Not a Prime Number");
}
}
}
}

Program in Python:

number = input(‘Please enter a number:’)
i = 2
toggle = 0
while i<number:
if number%i == 0:
toggle = 1
print ("Your number is NOT a prime number!");
i = i + 1
if toggle == 0:
print ("Your number is a prime number!");

If our post is helpful then share it with your near and dear ones.

No comments:

Post a Comment

Prove that you are Alive by Writing Comments

Scan this QR Code on LinkedIn

Scan this QR Code on LinkedIn