Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Rational {
- int x, y;
- static Rational[][] a;
- public static Rational CAN(Rational x) {
- int a = x.x;
- int b = x.y;
- Rational d= new Rational();
- if (a == 0) {
- d.y = 1;
- return d;
- }
- if (a < 0) {
- a = -a;
- }
- if (b < 0) {
- d.x = -d.x;
- d.y = -d.y;
- b = -b;
- }
- if (b < a) {
- int c;
- c = a;
- a = b;
- b = c;
- }
- while (a!=0 && (b % a) != 0) {
- b = a;
- a = b % a;
- }
- if(a!=0) {
- d.x /= a;
- d.y /= a;
- }
- return d;
- }
- public static Rational ADD(Rational x, Rational y) {
- Rational res;
- res=new Rational();
- res.x = x.x * y.y + y.x * x.y;
- res.y = y.y * x.y;
- return CAN(res);
- }
- public static Rational SUB(Rational x, Rational y) {
- Rational d= new Rational();
- d.x = -y.x;
- d.y=y.y;
- return ADD(x, d);
- }
- public static Rational MUL(Rational x, Rational y) {
- Rational res;
- res = new Rational();
- res.x = x.x * y.x;
- res.y = x.y * y.y;
- return CAN(res);
- }
- public static Rational DIV(Rational x, Rational y) {
- Rational d=new Rational();
- d.x = y.y;
- d.y = y.x;
- return MUL(x, d);
- }
- public static void swap_str(int x, int y, int n) {
- Rational c;
- int i;
- for (i = 0; i < n; i++) {
- c = a[x][i];
- a[x][i] = a[y][i];
- a[y][i] = c;
- }
- }
- public static void main(String[] args) {
- int i, j, fs = 1, k, sc;
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- Rational[] x = new Rational[n];
- Rational b;
- a = new Rational[n][n+1];
- for (i = 0; i < n; i++) {
- for (j = 0; j <= n; j++) {
- a[i][j] = new Rational();
- sc = in.nextInt();
- a[i][j].x = sc;
- a[i][j].y = 1;
- }
- }
- for (k = 0; k < n; k++) {
- if (k > 0) {
- for (j = k; j < n; j++) {
- Rational[] t = a[k];
- a[k]=a[j];
- a[j]=t;
- b = DIV(a[j][k - 1], a[k - 1][k - 1]);
- for (i = 0; i <= n; i++) {
- a[j][i] = SUB(a[j][i], MUL(b, a[k - 1][i]));
- }
- }
- }
- if (a[k][k].x == 0) {
- if (k + fs > n - 1) {
- System.out.printf("No solution\n");
- return;
- }
- swap_str(k, k + fs, n + 1);
- k--;
- fs++;
- } else {
- fs = 1;
- }
- }
- for (i = n - 1; i >= 0; i--) {
- x[i] = a[i][n];
- for (j = n - 1; j > i; j--) {
- x[i] = SUB(x[i], MUL(a[i][j], x[j]));
- }
- x[i] = DIV(x[i], a[i][i]);
- }
- for (i = 0; i < n; i++){
- System.out.println(x[i].x+"/"+x[i].y);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement