49 lines
1.8 KiB
Java
49 lines
1.8 KiB
Java
/*
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
|
|
*/
|
|
package lab14_calebfontenot;
|
|
|
|
/**
|
|
*
|
|
* @author caleb
|
|
*/
|
|
public class PrimeNumbers {
|
|
public static void main(String[] args)
|
|
{
|
|
System.out.println("The first 50 prime numbers are: \n");
|
|
printPrimeNumbers(50);
|
|
}
|
|
public static void printPrimeNumbers(int numberOfPrimes) {
|
|
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
|
|
int count = 0; // Count the number of prime numbers
|
|
int number = 1; // A number to be tested for primeness
|
|
|
|
//> Repeatedly find prime numbers
|
|
while (count < numberOfPrimes) {
|
|
//>> Print the prime number and increase the count
|
|
if (isPrime(number)) {
|
|
count++; // Increase the count
|
|
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
|
|
//>> Print the number and advance to the new line
|
|
System.out.printf("%-5d\n", number);
|
|
}
|
|
else {
|
|
System.out.printf("%-5d", number);
|
|
}
|
|
}
|
|
//>> Check if the next number is prime
|
|
number++;
|
|
}
|
|
}
|
|
public static boolean isPrime(int number) {
|
|
for (int divisor = 2; divisor <= number / 2; divisor++) {
|
|
if (number % divisor == 0) {
|
|
// If true, number is not prime
|
|
return false;
|
|
}
|
|
}
|
|
return true; // number is prime
|
|
}
|
|
}
|