
Junior Member
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.

Junior Member
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;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
String primeNumbers = "";
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)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers between 1 and n are:"/n);
System.out.println(primeNumbers);
}
}
To know more and deeper dive about the code running functionality, Checkout this blog post.

Member
Is this useful / helpfull?
Yes 
No
Prime Number algorithm Java
import java.util.*;
import java.lang.*;
class primenumber {
//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");
}
}
Tags for this Thread
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules
Protected by : ZB
BLOCK & StopForumSpam
Bookmarks