in Algorithms
636 views
0 votes
0 votes

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[6]$ is $2$, and $SPF[11]$ 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[1000];

void findSPF() {

    SPF[1] = 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 */
                }
            }
        }
    }
}

 

in Algorithms
636 views

1 Answer

2 votes
2 votes
  1. int SPF[1000];
  2.  
  3. void findSPF() {
  4.  
  5. SPF[1] = 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. }

3 Comments

Hi, can you explain what does last for loop do?
0
0
For the last loop, it will update all the multiples of the smaller number i, to it's all the dividend j with the spf of i.
0
0
check chatgpt...it has whole explanation
0
0

Related questions