Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class FindPrimes {
- public static void main(String[] args) {
- int[] numbers = new int[501]; // Instantiate an array
- printPrimeArray(countAndPrintPrimes(numbers)); // call 2 methods in one line
- }
- public static boolean isPrime(int input) {
- if (input % 2 == 0) {
- return false;
- } else {
- for (int i = 3; i*i <= input; i+=2) {
- if (input % i == 0) {
- return false;
- }
- }
- }
- return true;
- }
- public static void printPrimeArray(ArrayList<Integer> arlist) {
- for (int element : arlist) {
- System.out.println(element);
- }
- }
- public static ArrayList<Integer> countAndPrintPrimes(int[] inputArray) {
- int count = 0;
- for (int i = 0; i < inputArray.length; i++) {
- if (isPrime(i)) {
- count++;
- }
- }
- ArrayList<Integer> myPrimeNumbers = new ArrayList <>();
- for (int i = 0; i < inputArray.length; i++) {
- if (isPrime(i)) {
- myPrimeNumbers.add(i); // call ArrayList add() method
- }
- }
- return myPrimeNumbers;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement