Create a list of integers from 2 to n (e.g. 2, 3, 4, ..., n) For integers p in t
ID: 3813624 • Letter: C
Question
Create a list of integers from 2 to n (e.g. 2, 3, 4, ..., n) For integers p in the range [2, n/2], do the following: (a) If p is crossed off, skip the following step (b) otherwise, cross off all multiples of p in the list not including p itself-some of these numbers may already be crossed off and that's okay (e.g. 2p, 3p, 4p, ...) Each number in the list that wasn't crossed off is prime For example, if we run this algorithm on n = 10, we get the following steps At the end of this algorithm the numbers 2, 3, 5, and 7 are prime. You should implement this method using an Array List of Integers. You can simulate crossing out a number from the list by removing that element from the list. Be aware that ArrayList implements two different remove methods. remove (int) will remove an element at the index specified by the argument, and remove (Integer) will remove the first element equal to the object specified by the argument. Be careful which one you are calling! You are also responsible for writing a driver which will match the following sample output.Explanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
public class CrossList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter any integer:");
int num = sc.nextInt();
if(num<2){
System.out.println("Please run the Program for n>2");
System.exit(0);;
}
else
{
for(int m=2;m<=num;m++)
list.add(m);
}
for(int i=1;i<list.size();i++){
System.out.println();
if(!(list.get(i)==2 || list.get(i)==3)){
for(int k=0;k<list.size();k++){
if(!(list.get(k)==2 || list.get(k)==3))
if(list.get(k)%i==0)
list.remove(k);
}
}
System.out.print("Pass "+i+":");
for(int j=0;j<list.size();j++){
System.out.print(list.get(j)+" ");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.