Please Solve for (b + c) Q) Answer the questions regarding the following program
ID: 3574186 • Letter: P
Question
Please Solve for (b + c)
Q) Answer the questions regarding the following program
import java.util.ArrayList;
public class Eratosthenes {
public static void main(String []args) {
ArrayList<Integer> al = new ArrayList<>();
int n = 120;
for(int i = 0; i < n; i++) {
al.add(1);
}
al.set(0,0);
al.set(1,0);
for(int i = 2; i < n; i++) {
for(int j = 2; i*j < n; j++) {
al.set(i*j,0);
}
}
for(int i = 0; i < n; i++) {
if (al.get(i) > 0) {
System.out.println(i);
}
}
}
}
(a) Execute this program and submit the result
Answer:
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
101
103
107
109
113
(b) What are the common characteristics of the printed numbers. Explain briefly.
Answer: ???
(c) The following program execute the same algorithm as the above. Complete the following program.
import java.util.ArrayList;
public class Prime {
public static void main(String []args) {
ArrayList<Object> al = new ArrayList<>();
int n = 120;
for(int i = 0; i < n; i++) {
_________;
}
___________;
___________;
for(int i = 2; i < n; i++) {
for(int j = 2; i*j < n; j++) {
_____________;
}
}
for(int i = 0; i < n; i++) {
if (______________________) {
System.out.println(i);
}
}
}
}
Explanation / Answer
b) The output is a list of prime numbers between 0 to 120
c) Inorder to convert an object to int(Typecasting) you need to use (int) object .
import java.util.ArrayList;
public class Prime {
public static void main(String []args) {
ArrayList<Object> al = new ArrayList<>();
int n = 120;
for(int i = 0; i < n; i++) {
al.add(1);
}
al.set(0,0);
al.set(1,0);
for(int i = 2; i < n; i++) {
for(int j = 2; i*j < n; j++) {
al.set(i*j,0);
}
}
for(int i = 0; i < n; i++) {
if ((int) al.get(i) > 0) {
System.out.println(i);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.