184k views
1 vote
Unlike the harmonic numbers, the sum 1/12 + 1/22 + ... + 1/n? does converge to a constant as n grows to infinity. (Indeed, the constant is n/6, so this formula can be used to estimate the value of .) Which of the following for loops computes this sum? Assume that n is an int variable initialized to 1000000 and sum is a double variable initialized to 0.0.

1 Answer

4 votes

Step-by-step explanation:

None of the following for loops correctly computes the given sum:

for (int i = 1; i < n; i++) {

sum += 1/(i*i);

}

for (int i = 1; i <= n; i++) {

sum += 1/(i*i);

}

for (int i = 1; i <= n; i++) {

sum += 1.0/(i*i);

}

The correct for loop to compute the given sum is:

for (int i = 1; i <= n; i++) {

sum += 1.0/(i*i);

}

This loop correctly iterates from i=1 to i=n and uses the double data type to ensure that the division operation results in a decimal approximation.

User Rodnower
by
8.3k points