#include <iostream>
#include <iomanip>
#include <math.h>
usingnamespace std;
int main() {
double n1, n2, h1 = 0, h2 = 0, i; // n = number, h = harmonic
cin >> n1 >> n2;
if (n1 == 0) {
h1 = 0;
}
else {
for (i = 1; i <= n1; i++) {
h1 += 1 / i;
if (i <= n2) {
h2 += 1 / i;
}
}
}
cout << fixed << setprecision(10) << h1 - h2 << endl;
system("pause");
return 0;
}
The program gives correct results but I'm using a website of my university and it says that the program is slow. I've tried to make it faster but I can't figure out how.
Thanks.
Lets assume that m<n. The recurrence relation says that:
Hn == sum(1/a) + sum(1/b), where a=1..m and b=m+1..n
<=>
Hn == Hm + sum(1/b), where b=m+1..n
=>
x = sum(1/b), where b=m+1..n
Swapping input (n and m) merely changes the sign of the difference. That you can handle separately.
Can we assume that you know the difference between
1 / i
and
1.0 / i
?