tags:

views:

89

answers:

1
package Algorithms;
import cs1.Keyboard;
import java.util.*;

public class SieveofEratosthenes2 {
    public static void main (String[] args){

        //input number and create an array with the length of (num-1)
        int num = Keyboard.readInt();
        ArrayList prime = new ArrayList(num);

        //populate array with all numbers from 2 to num
        for(int i = 0; i < prime.size()-1; i++)
        {
            Integer temp = new Integer(i+2);
            prime.add(i, temp);
        }
        System.out.println(prime.size());
+7  A: 

The constructor here doesn't set the size of the ArrayList to num, it sets the capacity to num:

ArrayList prime = new ArrayList(num);

The size of the ArrayList is still zero, so your loop body never runs. Try this instead:

for (int i = 0; i < num - 1; i++)
{
    Integer temp = new Integer(i+2);
    prime.add(temp);
}

Definition of size:

the number of elements in this list.

Definition of capacity:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

Mark Byers