Farey Sequence | Efficient Java program to print Farey Sequence of order n ; Optimized function to print Farey sequence of order n ; We know first two terms are 0 / 1 and 1 / n ; double 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
class GFG { static void farey ( int n ) { double x1 = 0 , y1 = 1 , x2 = 1 , y2 = n ; System . out . printf ( " % .0f / % . 0f ▁ % .0f / % . 0f " , x1 , y1 , x2 , y2 ) ; while ( y != 1.0 ) { x = Math . floor ( ( y1 + n ) / y2 ) * x2 - x1 ; y = Math . floor ( ( y1 + n ) / y2 ) * y2 - y1 ; System . out . printf ( " ▁ % .0f / % . 0f " , x , y ) ; x1 = x2 ; x2 = x ; y1 = y2 ; y2 = y ; } } public static void main ( String [ ] args ) { int n = 7 ; System . out . print ( " Farey ▁ Sequence ▁ of ▁ order ▁ " + n + " isNEW_LINE"); farey ( n ) ; } }