-1
    public static void main(String[] args) {
    int limit = 100;
    System.out.println("Prime numbers between 1 and " + limit);
    for(int i=1; i < 100; i++){
        boolean isPrime = true;
        for(int j=2; j < i ; j++){

            if(i % j == 0){
                isPrime = false;
                break;
            }}
        // print the number 
        if(isPrime)
            System.out.print(i + " ");
    }}}

I want to compare the each element in the result .So i want to add this result into an array. How can i add the result of this program into a array?

Learner
  • 23
  • 1
  • 8

2 Answers2

1

You can use ArrayList to store all the prime numbers you found.

List primeNumbers = new ArrayList();

then add the number into list using 'add' method of the list.

if(isPrime){
  primeNumbers.add(i);
}
efex09
  • 417
  • 2
  • 12
0

You can use a lambda in java8. for example

List<Integer> primes = IntStream.rangeClosed(2, 100)
            .filter(i -> IntStream.rangeClosed(2, (int) Math.sqrt(i)).allMatch(j -> i % j != 0))
            .boxed().collect(toList());

    System.out.println(primes);
Gurinder
  • 943
  • 2
  • 9
  • 19
Faiz Akram
  • 559
  • 4
  • 10