Ulam Number Sequence | JAVA code to print nth Ulam number ; Array to store Ulam Number ; Function to compute ulam Number ; push First 2 two term of the sequence in the array for further calculation ; loop to generate Ulam number ; traverse the array and check if i can be represented as sum of two distinct element of the array ; If count is 2 that means i can be represented as sum of two distinct terms of the sequence ; i is ulam number ; Driver code ; pre compute Ulam Number sequence ; print nth Ulam number
import java . util . * ; class GFG { static final int MAX = 1000 ; static Vector < Integer > arr = new Vector < Integer > ( ) ; static void ulam ( ) { arr . add ( 1 ) ; arr . add ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr . size ( ) ; k ++ ) { if ( arr . get ( j ) + arr . get ( k ) == i ) { count ++ ; } if ( count > 1 ) break ; } if ( count > 1 ) break ; } if ( count == 1 ) { arr . add ( i ) ; } } } public static void main ( String [ ] args ) { ulam ( ) ; int n = 9 ; System . out . println ( arr . get ( n - 1 ) ) ; } }