Advertisement
Schnuk

Untitled

Feb 25th, 2021
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Fraction
  6. {
  7.     int numerator;
  8.     int denominator;
  9.     Fraction* next;
  10.  
  11.     Fraction(int numerator, int denominator, Fraction* next)
  12.     {
  13.         this->numerator = numerator;
  14.         this->denominator = denominator;
  15.         this->next = next;
  16.     }
  17.     Fraction()
  18.     {
  19.         next = nullptr;
  20.         numerator = 1;
  21.         denominator = 1;
  22.     }
  23. };
  24.  
  25. void OutputFareySequence(Fraction* array)
  26. {
  27.     Fraction* current = array;
  28.     while (current != nullptr)
  29.     {
  30.         cout << current->numerator << " / " << current->denominator << endl;
  31.         current = current->next;
  32.     }
  33. }
  34.  
  35. void GetFareySequence(Fraction* array, int n)
  36. {
  37.     array[1] = Fraction(1, 1, nullptr);
  38.     array[0] = Fraction(0, 1, &array[1]);
  39.     int newFractionPosition = 2;
  40.     for (int i = 2; i <= n; i++)
  41.     {
  42.         Fraction* current = array;
  43.         while (current->next != NULL)
  44.         {
  45.             if (current->denominator + current->next->denominator == i)
  46.             {
  47.                 int newFractionNumerator = current->numerator + current->next->numerator;
  48.                 int newFracTionDenominator = current->denominator + current->next->denominator;
  49.                 array[newFractionPosition] = Fraction(newFractionNumerator, newFracTionDenominator, current->next);
  50.                 current->next = &array[newFractionPosition++];
  51.             }
  52.             current = current->next;
  53.         }
  54.     }
  55. }
  56.  
  57. int main()
  58. {
  59.     struct Fraction array[10000];
  60.     int arraySize = sizeof(array) / sizeof(array[0]);
  61.     int n;
  62.     cout << "Enter n (array size "<< arraySize <<" elements)" << endl;
  63.     cin >> n;
  64.     GetFareySequence(array, n);
  65.     OutputFareySequence(array);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement