Farey Sequence | Efficient C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void farey ( int n ) { double x1 = 0 , y1 = 1 , x2 = 1 , y2 = n ; printf ( " % .0f / % . 0f ▁ % .0f / % . 0f " , x1 , y1 , x2 , y2 ) ; while ( y != 1.0 ) { x = floor ( ( y1 + n ) / y2 ) * x2 - x1 ; y = floor ( ( y1 + n ) / y2 ) * y2 - y1 ; printf ( " ▁ % .0f / % . 0f " , x , y ) ; x1 = x2 , x2 = x , y1 = y2 , y2 = y ; } } int main ( ) { int n = 7 ; cout << " Farey ▁ Sequence ▁ of ▁ order ▁ " << n << " ▁ is STRNEWLINE " ; farey ( n ) ; return 0 ; }