List of all available Websheets
Viewing cpp/references/vector_sum by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | In this exercise we improve an order of growth by using references. This program computes the millionth <i>harmonic number</i>, $$H_{1000000} = 1/1 + 1/2 + \cdots + 1/100000.$$ It adds the numbers in reverse order to get more numerical stability. |
Public permissions | |
Engine | |
Template / Reference solution |
using namespace std; // function to get Kth entry from end of vector // K=0 is last entry, K=1 is second-last, etc double kth_last_entry(\[vector<double>& vec\show:vector<double> vec]\, int K) { return vec[vec.size()-K-1]; } int main() { // create array 1/1, 1/2, ... 1/100000 vector<double> values; for (int i=1; i<=100000; i++) values.push_back(1.0/i); // add it in reverse order double sum = 0; for (int K=0; K<100000; K++) sum += kth_last_entry(values, K); cout << sum << endl; } |
C++ test suite json list of stdin/args tests e.g. [{"stdin":"hi", "args":["4", "5"]}, {"stdin":"noargs"}] to just run once with no input use [{}] | [ {} ] |
Solution visibility |
Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.