93 views

The following function computes an array $SPF$, where, for any integer $1 < i < 1000$,  $SPF[i]$ is the smallest prime factor of $i$. For example, $SPF$ is $2$, and $SPF$ is $11$.

There are five missing parts in the following code, commented as $/* Blank */$. For each of them, copy the entire line with the comment and fill the blank appropriately in your answer sheet.

int SPF;

void findSPF() {

SPF = 1;

// Initializing SPF of every number to be itself

for (int i = 2; i < 1000; i++) {
_____; /* Blank 1 */
}

// SPF of every even number is 2

for (int i = 4; i < 1000; i += 2) {

SPF[i] = _____; /* Blank 2 */
}

// For odd numbers, updating the SPFs of their multiples

for (int i = _____; i * i < 1000; i++) {

/* Blank 3 */

if (SPF[i] == i) {

// No smaller factor of i found yet

for (int j = _____; j < 1000; j+= i) {

/* Blank 4 */
if (SPF[j] == j) {

SPF[j] = _____; /* Blank 5 */
}
}
}
}
}

| 93 views

+1 vote
1. int SPF;
2.
3. void findSPF() {
4.
5. SPF = 1;
6.
7. // Initializing SPF of every number to be itself
8.
9. for (int i = 2; i < 1000; i++) {
10. SPF[i]=i; /* Blank 1 */
11. }
12.
13. // SPF of every even number is 2
14.
15. for (int i = 4; i < 1000; i += 2) {
16.
17. SPF[i] = 2; /* Blank 2 */
18. }
19.
20. // For odd numbers, updating the SPFs of their multiples
21.
22. for (int i = 3; i * i < 1000; i++) {
23.
24. /* Blank 3 */
25.
26. if (SPF[i] == i) {
27.
28. // No smaller factor of i found yet
29.
30. for (int j = i; j < 1000; j+= i) {
31.
32. /* Blank 4 */
33. if (SPF[j] == j) {
34.
35. SPF[j] = SPF[i]; /* Blank 5 */
36. }
37. }
38. }
39. }
40. }