Prime Number in Java


Prime no.

A number is called prime number if its not divisible by any number other than 1 or itself and you can use this logic to check whether a number is prime or not.It is called a composite number.

 

//Write a program of Prime Number in Java

import java.util.*;
class Prime
{
public static void main(String args[])
{
int n, i, res;
boolean flag=true;
Scanner scan= new Scanner(System.in);
System.out.println(“Please Enter a No.”);
n=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println(n + ” is Prime Number”);
else
System.out.println(n + ” is not Prime Number”);
}
}

output:

prime

 

 

 

 

 

 

 

 

 

 

This PrimeNumber program shows how to generate prime numbers between 1 and given number using for loop.

 

//Java program of PrimeNumbers in a given range.

import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
System.out.println(“Enter the number till which prime number to be printed: “);
int limit = new Scanner(System.in).nextInt();

System.out.println(“Printing prime number from 1 to ” + limit);
for(int number = 2; number<=limit; number++)
{
//print prime numbers only
if(isPrime(number))
{
System.out.println(number);
}
}
}
public static boolean isPrime(int number)
{
for(int i=2; i<number; i++)
{
if(number%i == 0)
{
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}

output:

primeno

Related Posts

Comments are closed.