Farey Sequence | Optimized function to print Farey sequence of order n ; We know first two terms are 0 / 1 and 1 / n ; var x , y = 0 ; For next terms to be evaluated ; Using recurrence relation to find the next term ; Print next term ; Update x1 , y1 , x2 and y2 for next iteration ; Driver program
function farey ( n ) { var x1 = 0 , y1 = 1 , x2 = 1 , y2 = n ; document . write ( x1 + " " + y1 + " " + x2 + " " + y2 + " " ) ; while ( y != 1.0 ) { x = Math . floor ( ( y1 + n ) / y2 ) * x2 - x1 ; y = Math . floor ( ( y1 + n ) / y2 ) * y2 - y1 ; document . write ( x + " " + y + " " ) ; x1 = x2 ; x2 = x ; y1 = y2 ; y2 = y ; } } var n = 7 ; document . write ( " " + n + " " ) ; farey ( n ) ;