A prime number is the number which is is divisible by itself and not by
other numbers.
A program to check prime number can be made by using for and while loop
combination .
This article contains java program for finding prime number ,write a java program for prime number between 1- 100 ,simple program to find prime factorial of a number in java.
EXAMPLE 1 -
program to check whether a number is prime number or not.
import java.util.*;
public class pr
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter number");
int num=sc.nextInt();
int d=0;
for(int i=2;i<=num;i++)
{
if(num%i==0)
d++;
}
if(d==0)
System.out.println("it is a prime number");
else
System.out.println("it is not a prime number");
}
}
Output
enter number
23
it is a prime number
A prime factorial of a number is the products of all the prime numbers less than
the number.
EXAMPLE 2 -
program to get prime factorial of a number
import java.util.*;
public class primorial
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
int sum=1;
primorial m=new primorial();
for(int i=2;i<=n;i++)
{
if(m.checkPrime(i)==true)
{
sum=sum*i;
}
}
System.out.println("prime factorial of "+n+" is: "+sum);
}
boolean checkPrime(int a)
{
int d=0;
for(int i=2;i<a;i++)
{
if(a%i==0)
d++;
}
if(d==0)
return true;
else
return false;
}
}
Output
enter a number
23
prime factorial of 23 is : 111546435
EXAMPLE 3-java program to find primenumbers between 1 and 100import java.util.*;Public class primecheck{public static void main(){Scanner sc=new Scanner(System.in);System.out.println("prime numbers are:");primecheck m=new primecheck();for(int i=2;i<=100;i++){if(m.checkPrime(i)==true){System.out.println(i);}}}boolean checkPrime(int a){int d=0;for(int i=2;i<a;i++){if(a%i==0)d++;}if(d==0)return true;elsereturn false;}}OutputPrime number are: 357111317192329313741434753596167717379838997If you find this helpful please share
Comments
Post a Comment