Advertisement
Schnuk

Untitled

Feb 25th, 2021
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 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.  
  18.     Fraction() {}
  19. };
  20.  
  21. void OutputFareySequence(Fraction* array)
  22. {
  23.     Fraction* current = &array[0];
  24.     while (current != NULL)
  25.     {
  26.         cout << current->numerator << " / " << current->denominator << endl;
  27.         current = current->next;
  28.     }
  29. }
  30.  
  31. void ClearMemory(Fraction** memoryArray)
  32. {
  33.     for (int i = 0; i < 100; i++)
  34.         delete memoryArray[i];
  35. }
  36.  
  37. void GetFareySequence(Fraction* array, int n, Fraction** memoryArray)
  38. {
  39.     memoryArray[0] = new Fraction(0, 1, &array[1]);
  40.     memoryArray[1] = new Fraction(1, 1, NULL);
  41.     array[1] = *memoryArray[1];
  42.     array[0] = *memoryArray[0];
  43.     int newFractionPosition = 2;
  44.     for (int i = 2; i <= n; i++)
  45.     {
  46.         Fraction* current = &array[0];
  47.         while (current->next != NULL)
  48.         {
  49.             if (current->denominator + current->next->denominator == i)
  50.             {
  51.                 int newFractionNumerator = current->numerator + current->next->numerator;
  52.                 int newFracTionDenominator = current->denominator + current->next->denominator;
  53.                 Fraction* newFraction = new Fraction(newFractionNumerator, newFracTionDenominator, current->next);
  54.                 memoryArray[newFractionPosition] = newFraction;
  55.                 current->next = newFraction;
  56.                 array[newFractionPosition++] = *newFraction;
  57.             }
  58.             current = current->next;
  59.         }
  60.     }
  61. }
  62.  
  63. int main()
  64. {
  65.     for (int i = 0; i < 10000; i++)
  66.     {
  67.         struct Fraction array[10000];
  68.         const int arraySize = sizeof(array) / sizeof(array[0]);
  69.         Fraction* memoryArray[arraySize];
  70.         for (int i = 0; i < 100; i++)
  71.             memoryArray[i] = nullptr;
  72.         int n = 10;
  73.         //cout << "Enter n (array size 100 elements)" << endl;
  74.         //cin >> n;
  75.         GetFareySequence(array, n, memoryArray);
  76.         OutputFareySequence(array);
  77.         ClearMemory(memoryArray);
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement