Reputation: 119
"We don't need to enumerate the fractions in any particular order we just need to make sure that as long as the loop keeps going every rational number will eventually be constructed. So what about:
for i=0 to infinity
for j=1 to i
display i/j
next j
next i
You should be able to see that if you wait long enough every fraction will eventually be displayed. In fact we are generating each fraction an infinite number of times because of identical terms like 1/2, 2/4. 4/8 and so on.."
Why the output is 1/2, 2/4 and so on... ? I can't figure out :(( Translate this pseudocode into C or C++ language, maybe I didn't it right:
#include <stdio.h>
int main()
{
for (int i = 0; i < 100000000000000000; i++) {
for(int j = 1; j < i; j++) {
printf("%f\n", (float)(i/j));
}
}
return 0;
}
Upvotes: 0
Views: 82
Reputation: 17389
I assume you're referencing this sentence:
In fact we are generating each fraction an infinite number of times because of identical terms like 1/2, 2/4. 4/8 and so on.."
That does NOT say the output is 1/2, 2/4, 4/8. It's just saying that any particular fraction, 1/2 for example, appears an infinite amount of times in the output. I.e. 1/2 == 2/4 == 4/8 == ... and so on.
Upvotes: 2
Reputation: 500933
i/j
returns integer result (which you then cast to float
).
Change
(float)(i/j)
to
((float)i)/j
Also, depending on the range of the int
type on your platform, 100000000000000000
is likely to be too large to fit in an int
.
Upvotes: 4