Java Tutorial For Beginner ~ Displaying Prime Numbers

in #programming7 years ago


This tutorial explains a program that displays the first twenty prime numbers in four lines,
each containing 5 numbers.

The key to developing a programmatic solution for this problem, and for many other problems, is to break it into subproblems and develop solutions for each of them in turn. Do not attempt to develop a complete solution in the first trial. Instead, begin by writing the code to determine whether a given number is prime, then expand the program to test whether other numbers are prime in a loop.

To determine whether a number is prime, check whether it is divisible by a number between
2 and number/2 inclusive.
If so, it is not a prime number;
otherwise, it is a prime number.
For a prime number, display it.
If the count is divisible by 5,
advance to a new line.
The program ends when the count reaches 20.

The program uses the break statement to exit the for loop as soon as the number is found to be a nonprime. You can rewrite the loop without using the break statement, as follows:

for (int divisor = 2; divisor <= number / 2 && isPrime;divisor++) {
if (number % divisor == 0) {
isPrime = false;
}
}

Using the break statement makes the program simpler and easier to read in this case.
I hope you hope understand this tutorial, should you not, please, drop your question and i will be explaining the area that you don't understand to you.

Our next tutorial will be on methods. Stay tuned!!!

Here is the code;
public class PrimeNumber {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 20;
final int NUMBER_OF_PRIMES_PER_LINE = 5;
int count = 0;
int number = 2;
System.out.println("The first 20 prime numbers are \n");
while (count < NUMBER_OF_PRIMES) {
boolean isPrime = true;
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}


▶️ DTube
▶️ IPFS