Simple program to find Prime number
I want to find it out for the number
2345678901233.. but it is giving the error ..is there any method to find out the primes beyond the range of integer..
import java.util.*;
public class inc {
int flag=0;
int h=2;
public void checkprime(int k)
{
while(h<k){
if(k%h==0){
flag=1;
}
h++;
}
if(flag==1 ||k==1 )
System.out.println("The number is not prime");
else
System.out.println("The number is prime");
}
public static void main(String[] args) {
inc a=new inc();
Scanner i=new Scanner(System.in);
int j=i.nextInt();
a.checkprime(j);
}
}
amit.hak50
Junior Poster in Training
65 posts since Dec 2009
Reputation Points: 10
Solved Threads: 0
Well a few things on your program.
You probably want it to exit the loop when it determines it is not-prime so you get the result faster. Really large number can take awhile to find if they are prime so you could be talking about several seconds,tens of seconds, or minutes of getting a result quicker.
Secondly you use h < k/2 because 2 is the minimum number you are going to divide the prime by but fact is after you divide by 3 if h > k/3 it also can't be prime so to expedite that I'd reccomend something like:
class Prime
{
public boolean isPrime(long number)
{
public boolean isPrime = false;
public long counter = 2;
while(counter < number/counter)
{
if(number%counter == 0)
{
isPrime = true;
break;
}
return isPrime;
}
}
public static void main(string[] argz)
{
Prime a = new Prime();
long b = 2345678901233;
if(a.isPrime(b))
System.out.println("Number is Prime");
else
System.out.println("Number is not Prime");
}
All of these are brute force methodologies and very slow in comparison to other algorithms but if you got a cup of copy and a couple dozen minutes feel free : )
ChaseRLewis
Junior Poster in Training
76 posts since Nov 2009
Reputation Points: 7
Solved Threads: 2
ChaseRLewis - you are on the right track, and you can tight the bound even more by summing all the integers up to sqrt(n) instead of up to k/3, as can be seen here
apines
Practically a Master Poster
633 posts since Apr 2007
Reputation Points: 129
Solved Threads: 55