package com.numericmethods;
import java.util.*;

public class LU{
	public static double[][] rozklad(int n, double[][] a) {  //n wymiarowa macierz A
	double[][] L = new double[n][n];
	double[][] U = new double[n][n];
	for(int i=0;i<L.length;i++){  //wypelniam diagonalie jedynkami
		L[i][i]=1;
	}
	int m=a.length;
	for(int j=0;j<=m-1;j++){
			for(int i=0;i<=j;i++){
				double sum=0;
				for(int k=0;k<=i-1;k++){
					sum+=L[i][k]*U[k][j];
				}
				U[i][j]=a[i][j]-sum;
			}
			for(int i=j+1;i<=m-1;i++){
				double sum=0;
				for(int k=0;k<=j-1;k++){
					sum+=L[i][k]*U[k][j];
				}
				L[i][j] = (a[i][j] - sum) / U[j][j];
			}
	} 
	
	System.out.println("L=" + Arrays.deepToString(L));
		return U;
	}
	
	public static void main(String[] args){
		System.out.println("Jaki rozmiar macierzy?");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt(); //pobrac rozmiar
		double[][] m = new double[n][n];
		for(int i=0;i<=n-1;i++){
			for(int j=0;j<=n-1;j++){
				System.out.println("Wprowadź wartość= [" + i +"]" + "[" + j + "]");
				m[i][j]=sc.nextDouble();
			}
		}
		System.out.println("Wprowadzona macierz A="+ Arrays.deepToString(m));
		System.out.println("Rozkład A=L*U");
	               System.out.println("U="+ Arrays.deepToString(rozklad(n,m))); 
	}
}