Farey Sequence | Optimized function to print Farey sequence of order n ; We know first two terms are 0 / 1 and 1 / n ; 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 Code
< ? php function farey ( $ n ) { $ x1 = 0 ; $ y1 = 1 ; $ x2 = 1 ; $ y2 = $ n ; echo $ x1 , " / " , $ y1 , " ▁ " , $ x2 , " / " , $ y2 , " ▁ " ; $ x ; $ y = 0 ; while ( $ y != 1.0 ) { $ x = floor ( ( $ y1 + $ n ) / $ y2 ) * $ x2 - $ x1 ; $ y = floor ( ( $ y1 + $ n ) / $ y2 ) * $ y2 - $ y1 ; echo $ x , " / " , $ y , " ▁ " ; $ x1 = $ x2 ; $ x2 = $ x ; $ y1 = $ y2 ; $ y2 = $ y ; } } $ n = 7 ; echo " Farey ▁ Sequence ▁ of ▁ order ▁ " , $ n , " ▁ is STRNEWLINE " ; farey ( $ n ) ; ? >