Triangle of numbers arising from Gilbreath 's conjecture | Java code for printing the Triangle of numbers arising from Gilbreath 's conjecture ; Check whether the number is prime or not ; Set the 0 th row of the matrix with c primes from 0 , 0 to 0 , c - 1 ; Find the n , k term of matrix of Gilbreath 's conjecture ; recursively find ; store the ans ; Print first n terms of Gilbreath sequence successive absolute differences of primes read by antidiagonals upwards . ; map to store the matrix and hash to check if the element is present or not ; set the primes of first row ; print the Gilbreath number ; increase the count ; anti diagonal upwards ; Driver code
import java . util . * ; public class GFG { static boolean is_Prime ( int n ) { if ( n < 2 ) return false ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static void set_primes ( HashMap < Integer , HashMap < Integer , Integer > > mp , HashMap < Integer , HashMap < Integer , Integer > > hash , int c ) { int count = 0 ; for ( int i = 2 ; count < c ; i ++ ) { if ( is_Prime ( i ) ) { if ( ! mp . containsKey ( 0 ) ) { mp . put ( 0 , new HashMap < Integer , Integer > ( ) ) ; } if ( ! mp . get ( 0 ) . containsKey ( count ) ) { mp . get ( 0 ) . put ( count , i ) ; } else { mp . get ( 0 ) . put ( count , i ) ; } count ++ ; if ( ! hash . containsKey ( 0 ) ) { hash . put ( 0 , new HashMap < Integer , Integer > ( ) ) ; } if ( ! hash . get ( 0 ) . containsKey ( count - 1 ) ) { hash . get ( 0 ) . put ( count - 1 , 1 ) ; } else { hash . get ( 0 ) . put ( count - 1 , 1 ) ; } } } } static int Gilbreath ( HashMap < Integer , HashMap < Integer , Integer > > mp , HashMap < Integer , HashMap < Integer , Integer > > hash , int n , int k ) { if ( hash . containsKey ( n ) && hash . get ( n ) . containsKey ( k ) && hash . get ( n ) . get ( k ) != 0 ) return mp . get ( n ) . get ( k ) ; int ans = Math . abs ( Gilbreath ( mp , hash , n - 1 , k + 1 ) - Gilbreath ( mp , hash , n - 1 , k ) ) ; if ( ! mp . containsKey ( n ) ) { mp . put ( n , new HashMap < Integer , Integer > ( ) ) ; } mp . get ( n ) . put ( k , ans ) ; return ans ; } static void solve ( int n ) { int i = 0 , j = 0 , count = 0 ; HashMap < Integer , HashMap < Integer , Integer > > mp = new HashMap < Integer , HashMap < Integer , Integer > > ( ) ; HashMap < Integer , HashMap < Integer , Integer > > hash = new HashMap < Integer , HashMap < Integer , Integer > > ( ) ; set_primes ( mp , hash , 100 ) ; while ( count < n ) { System . out . print ( Gilbreath ( mp , hash , i , j ) + " , ▁ " ) ; count ++ ; i -- ; j ++ ; if ( i < 0 ) { i = j ; j = 0 ; } } } public static void main ( String [ ] args ) { int n = 15 ; solve ( n ) ; } }