Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime Number Sequence Java

Tags:

java

So what my program does is that it reads user input and prints out a series of prime numbers that leads up to the input. So for example, if I input 20 the sequence should print out 2 5 7... etc. until it reaches 19 (since 20 is not a prime number) The only issue is when I run the program 1 keeps on printing out. Here is my method for figuring out whether a number is prime or not.

 public boolean isPrime(int number)
{  
    int prime;
    for(prime = 2; prime < number; prime++)
    { 
      if (number % prime == 0)
      { 
          if(number == 1)
          { 
              return false; 
          }
       return false;
      }
    }
    return true;
}

I have read multiple forums and solutions and none seem to help. I am completely stuck.

like image 979
xiomy528 Avatar asked Sep 26 '26 03:09

xiomy528


1 Answers

Putting

if (number < 2) return false;

as the first statement into your method should do the trick.

like image 167
luk2302 Avatar answered Sep 28 '26 18:09

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!