"How to write an algorithm that, given the number n, yields all simplified vulgar fractions that have the denominator 1..n"
(I hope I could formulate it correctly, feel free to rephrase.)
Example: If n is 3, the result should be like "1/2 1/3 2/3"
We talked about this issue at the end of the last class. He showed us the solution and asked us to understand the code. Here he is:
#include<stdio.h> void main() { int p,m,n,i,j,a,b; p=7; m=0; n=1; do { printf("%d/%d\n",m,n); i=j=1; for(b=2; b<=p; b++) { a=m*b/n+1; if(a*j<b*i) { i=a; j=b; } } m=i; n=j; } while(i<j); }
I am new to C and just learning the code, to be honest, I couldn't figure out what this code was doing. And he also prints "0/1", I also wonder why this is so, I think that this should not print it.
Here is my basic approach to this problem:
"n" is 7 in both codes. I checked the runtime with much larger numbers, and my algorithm is faster than the other. Therefore, I do not understand why another code is needed. Any suggestions / corrections about my code are also welcome.
source share