Skip to content

Instantly share code, notes, and snippets.

@smnatale
Last active June 4, 2020 22:04
Show Gist options
  • Select an option

  • Save smnatale/28545bc6949f7e4078ac8697555dc540 to your computer and use it in GitHub Desktop.

Select an option

Save smnatale/28545bc6949f7e4078ac8697555dc540 to your computer and use it in GitHub Desktop.
Codecademy Challenge - Program checks if any of the numbers in an Array are Prime Numbers
import java.util.ArrayList;
class PrimeDirective {
/* This checks if the number is prime by first checking if the number is 0 or less than 0, which makes it not prime.
It then checks if the number is divisible by every number from 3 to itself -1, if it is divisible it sets the return as false as it cannot be a prime number, it it is not the value remains as true */
public boolean isPrime(int num){
boolean value = true;
if (num <= 0) value = false;
for (int i=3; i < num; i++){
if (num % i == 0){
value = false;
}
}
System.out.println("The number " + num + " is prime: " + value);
return value;
}
public static void main(String[] args) {
// Array where the prime numbers will be stored
ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
PrimeDirective pd = new PrimeDirective();
// List of the numbers to check
int[] numbers = {7, 28, 29, 2, 0, 100, 101, 43, 89};
// For loop which will run the isPrime for each number in the list
for (int i=0; i < (numbers.length); i++){
// Temporary value which stores true/false depending if the number is prime
boolean temp = pd.isPrime(numbers[i]);
// If the number is prime it will be added to the primeNumbers ArrayList
if (temp == true){
primeNumbers.add(numbers[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment