Faster Harmonic Number?

I am trying to make a program that given two numbers it substracts one harmonic from the other. (Input: n, m / Output: Hn-Hm)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace 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.
Last edited on
"Harmonic number". Is it this: https://en.wikipedia.org/wiki/Harmonic_number ?

If yes, then the n and m seem to be integers.

Let x = Hn - Hm
=>
Hn == Hm + x

Hn == sum(1/k), where k=1..n

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
?
Topic archived. No new replies allowed.