-4

Please have a look at the following code

public class Prime
{
    public static void main(String[]args)
    {
        int i = 2; 
        int counter = 0;

        while(true)
        {


            if(counter==6)//Count still 6
            {
                break;
            }
            else
            {
                if(getPrimes(i)==true)
                {

                    i++;
                    counter++;
                    System.out.println("Counter: "+counter);
                }
                else
                {
                    System.out.println("No");
                }
            }
        }
    }

    static boolean getPrimes(int num)
    {

        boolean result = false;
        int i = 2;

            while(true)
            {
                if((num%i) != 0) //if the number cannot be divided by any other number (except 1 and it self) it is prime
                {
                    result = true;
                    System.out.println(num);
                    System.out.println("I is: "+i);
                    i=2;
                    break;
                }

                else //Not a prime. Repeat the process
                {
                    result = false;
                    i++;
                }
            }

            return result;
     }       
}

In here, I am trying to get all the prime numbers between 0-6. This is the test case to get thousands of prime numbers from a really big number. However, it is not showing the only primes, it is showing each and every number!

What am I doing here wrong? Please help!

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • http://stackoverflow.com/questions/2385909/most-elegant-way-to-write-isprime-in-java – Sturm Jul 01 '12 at 08:12
  • The answers address your primes issue. There's another one: Your main loop will get stuck and continue endlessly if `getPrimes` ever returns `false`, as you never increment `i` or `counter` in that case. Separately, any time you write `write (true)`, you should step back and look at your logic more closely. 99% of the time, there's a more intelligent termination condition you can put in the control structure. The 1% case exists, but it's rare. – T.J. Crowder Jul 01 '12 at 08:14
  • 1
    @MarkByers: That is the question I always hate! No IT IS NOTTTTTTT. Just a small stuff i do to build up my IQ – PeakGen Jul 01 '12 at 09:08
  • @Sepala: I was not attempting to offend you. I was only trying to help you to clarify your question. In future, you could try to remember to put this information into your question from the start as this will a) help people post more appropriate answers for your situation and b) will avoid people needing to ask "the question you hate" because you've already told them the answer. – Mark Byers Jul 01 '12 at 09:16
  • I suggest you step through your code in your debugger as this will help you understand what each line of code does. – Peter Lawrey Jul 01 '12 at 09:17
  • 2
    @Sepala: u should break from the code when the number u found the no to be checked is composite ....rather than i think u did it in the other way..... – Arjun K P Jul 01 '12 at 09:20
  • @MarkByers: oops..Hey, I normally use Uppercase as a habbit. I didn't mean "shout". I never do that for anyone who help me. Sorry if I hurt you :( – PeakGen Jul 01 '12 at 10:39
  • @MarkByers: Hello mark, where is your answer? I can't find it!.. Again, I am so sorry if I hurt u :( . I am an emotional person anyway :( – PeakGen Jul 01 '12 at 18:00
  • @Sepala: I was not hurt. It's just that no-one here thought my answer was a good or useful answer and it attracted zero upvotes. So I deleted it and upvoted akp's instead. There is no point cluttering the site with answers that no-one wants. It's not a particularly unusual thing - in fact four other people also deleted their answers to this question. – Mark Byers Jul 01 '12 at 18:08
  • @MarkByers....i don't know what was going here...but hey...thanks for ur upvotes..... – Arjun K P Jul 01 '12 at 18:35

6 Answers6

4

try this answer...in ur loop

static boolean getPrimes(int num)
{

    boolean result=true;     // incase u gave 1 or 2 as input.....
    int i = 2;
    int mid=num/2; 

    while(i<mid)
    {
         if(num%i==0)
         {
               result=false;   // not a prime and breaks...
               break;
         }
         else
         {
               result=true;    // the loop make result as true.....  

         }
         i++;
     }
     return result;
}
Arjun K P
  • 2,081
  • 4
  • 20
  • 33
2

I think you need something like this:

public void getPrimes(int a){
    for(int i = 2; i < a; i++){
        int inCounter = 0;
        if(counter%i==0){
            System.out.println("false");
            inCounter++;
        }
        if(inCounter == 0){
            System.out.println("Prime: "+counter);
        }
    }
}
FabianCook
  • 20,269
  • 16
  • 67
  • 115
0

Use a sieve, either Eratosthenes or Atkins

Here's the Eratosthenes implementation by Robert Sedgewick in Java:

http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

I guess I found the solution. At least, I found the answer I need. Here is my answer

import java.math.BigInteger;

public class Problem7
{
    public static void main(String[]args)
    {
        int i = 0;
        int counter = 0;

        while(true)
        {

            if(i>6)
            {
                break;
            }

            if(i>1)
            {
                String str = String.valueOf(i);

                if (new BigInteger(str).isProbablePrime(i/2))
                {
                    System.out.println(str);
                     counter++;
                }
            }
            i++;

        }

    }
}

I guess this is the easiest way...

PeakGen
  • 21,894
  • 86
  • 261
  • 463
0
import java.util.Scanner;
class PrimeNumbers2
{
   public static void main (String[] args)
   {        
      Scanner scanner = new Scanner(System.in);
      int i =0;
      int num =0;
      //Empty String
      String  primeNumbers = "";
      System.out.println("Enter the value of n:");
      int n = scanner.nextInt();
      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)
     {
        //Appended the Prime number to the String
        primeNumbers = primeNumbers + i + " ";
     }  
      } 
      System.out.println("Prime numbers from 1 to n are :");
      System.out.println(primeNumbers);
   }
}

it will display all the prime number.

Joya
  • 1
  • 1
0

Find Prime number with minimum iteration

boolean IsPrimeNumber(int num) {

    boolean isPrime = true;
    if (num == 1 || num ==0)
        isPrime = false;
    else{

        int limit = (int) Math.sqrt(num);
        for (long i = 2L; i <=limit ; i++)
            if (num % i == 0) {
                isPrime = false;
                break;
            }
    }

    return isPrime;

}
amoljdv06
  • 2,646
  • 1
  • 13
  • 18