# Thread: Prime Number Algorithm in Java

1. ## Prime Number Algorithm in Java

Hello All, I want to know prime number algorithms. If I have 1 to 100 number how I can find the prime number in scanner? Can anyone know about it, If yes then please tell me how to identify the prime number program in java. I have checked some references to get a program of scanner but i didn't an example.  Reply With Quote

2. Is this useful / helpfull? Yes | No
Hi Arjun,

It is very simple program, Before starting the logic of the prime number program, you must need to know that what is prime number?
A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.

The number that is divisible by one or by themselves is known as a prime number.

2
3
5
7
11
13
17
19
23

Now about the program using Ja
import java.util.Scanner;
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
System.out.println("Enter a number:");
int n = scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
}
}
System.out.println("Prime numbers between 1 and n are:"/n);
}
}

To know more and deeper dive about the code running functionality, Checkout this blog post.  Reply With Quote

3. Is this useful / helpfull? Yes | No
Prime Number algorithm Java

import java.util.*;
import java.lang.*;

//check for number prime or not
static boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i<=Math.sqrt(n);i+=2) {
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args)
{
if(isPrime(19))
System.out.println(" true") ;

else
System.out.println(" false");

}
}  Reply With Quote

programming 