Java exercises:

I received some java exercises on email, and I wanted to give them a try. I’m posting my solution to excercise “1. Prime Numbers“ since it the mail said “Feel free to share your solutions“ in this forum. I would like to see other persons solutions so I can improve.

  1. Prime Numbers

Create a function that returns a list of all prime numbers up to a given number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, and 11 are prime numbers.

My solution:

public class App {
    public static void main(String[] args) throws Exception {
        System.out.println(primeNumbers(100));

    }

    public static List<Integer> primeNumbers(int toNum) {

        List<Integer> primeNumbers = new ArrayList<>();

        for (int i = 2; i <= toNum; i++) {
            int divisibleCount = 0;
            //System.out.println(i);

            for (int j = i; j >= 1; j--) {

                if (i % j == 0) {
                    //System.out.println(i + " is divisible by " + j);
                    divisibleCount++;
                }

                if (divisibleCount > 2) {
                    //System.out.println("divisible count is " + divisibleCount + " no need to count further");
                    break;
                }

            }
            if (divisibleCount <= 2) {
                primeNumbers.add(i);
            }
        }

        return primeNumbers;

    }
}

Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

I would use an algorithm that counts divisor integers up to half of the number being tested. - Bruce W.

2 Likes

Sorry - I meant the square root of the number.

2 Likes