Advertisement
Guest User

Untitled

a guest
Dec 17th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <stdio.h>
  4.  
  5. using namespace std;
  6.  
  7. struct nr{
  8. int p;
  9. int q;
  10. };
  11.  
  12. void affiche(nr nombre){
  13. if(nombre.q == 1){
  14. cout << nombre.p << endl;
  15. } else {
  16. cout << nombre.p << "/" << nombre.q << endl;
  17. }
  18. }
  19.  
  20. int pgcd(int a, int b){
  21. int prev_u(1), prev_v(0), x(a), y(b), u(0), v(1);
  22. int new_u, new_v, q, r;
  23.  
  24. /* Juste pour info. Normalement une telle fonction NE doit RIEN
  25. * afficher (« effet de bord ») !
  26. */
  27.  
  28. while (y != 0) {
  29. q = x/y;
  30. r= x%y;
  31. x = y;
  32. y = r;
  33. new_u = prev_u - u * q;
  34. prev_u = u;
  35. u = new_u;
  36. new_v = prev_v - v * q;
  37. prev_v = v;
  38. v = new_v;
  39.  
  40. /* Juste pour info. Normalement une telle fonction NE doit RIEN
  41. * afficher (« effet de bord ») !
  42. * L'affichage est ici approximatif. Pour faire mieux il faudrait
  43. * utiliser setw (présenté plus tard en cours)
  44. */
  45.  
  46. }
  47.  
  48. return x;
  49. }
  50.  
  51. nr reduction(nr x){
  52. int co = pgcd(x.p,x.q);
  53. x.p /= co;
  54. x.q /= co;
  55. if(x.q < 0 and x.p > 0){x.p *= -1; x.q *= -1;}
  56.  
  57. return x;
  58. }
  59.  
  60. nr addition(nr r1, nr r2){
  61. nr a = {(r1.p*r2.q+r2.p*r1.q), (r1.q*r2.q)};
  62. return reduction(a);
  63. }
  64.  
  65. nr soustraction(nr r1, nr r2){
  66. nr a = {(r1.p*r2.q-r2.p*r1.q), (r1.q*r2.q)};
  67. return reduction(a);
  68. }
  69.  
  70. nr multiplication(nr r1, nr r2){
  71. nr a = {(r1.p*r2.p), (r1.q*r2.q)};
  72. return reduction(a);
  73. }
  74.  
  75. nr division(nr r1, nr r2){
  76. if (r2.p == 0){
  77. throw string ("divided by 0");
  78. }
  79. if(r2.p < 0){
  80. nr a = {-(r1.p)*r2.q ,(r1.q*(-r2.p))};
  81. return reduction(a);
  82. } else {
  83. nr a = {r1.p*r2.q,(r1.q*(-r2.p))};
  84. return reduction(a);
  85. } // else {nr a = {0,0}; return a;}
  86.  
  87. }
  88.  
  89. int main()
  90. {
  91. nr a = {1, 2};
  92. nr b = {0, 5};
  93. affiche(a);
  94. affiche(b);
  95. try{
  96. affiche(division(a,b));
  97. }
  98. catch (string error){
  99. cerr << error << endl;
  100. return 1;
  101. }
  102. return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement