I need to get some information about the Pascal Triangle.
What is a pascal triangle ?
It is a triangle of integers with 1 at the top and at the sides. Any number inside is equal to the sum of the two numbers above his. For example, here are the first 5 lines of the triangle:
So I need to figure out the number of numbers pairs that exist in the first thousand lines of the triangle.
I would like to know how I can improve the performance of my code or rewrite some part that is poorly structured
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;
public class PascalTriangle {
private static int [][] matrix;
private static int i, j, n;
public static void main(String[] args)
{
long start_time = System.currentTimeMillis();
n = 0; // Number of even numbers;
matrix = new int[1000][1000];
for (i = 0; i < 1000; i++) {
for (j = 0; j < 1000; j++) {
matrix[i][j] = 0;
}
}
matrix[0][0] = 1;
matrix[1][0] = 1;
matrix[1][1] = 1;
for (i = 2; i < 1000; i++) {
matrix[i][0] = 1;
matrix[i][i] = 1;
for (j = 1; j < i; j++) {
matrix[i][j] = matrix[i-1][j-1]+matrix[i-1][j];
if ( matrix[i][j] % 2 == 0 ) {
n++;
}
}
}
System.out.println( "Amount of even numbers = " + n );
long end_time = System.currentTimeMillis();
System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end_time - start_time)));
}
}
Expected result:
Amount of even numbers = 448363
Currently taking a time of 00.011 seconds