Ulam Number Sequence | JAVA code to print nth Ulam number ; Array to store Ulam Number ; function to compute ulam Number ; Set to search specific Ulam number efficiently ; push First 2 two term of the sequence in the array and set 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 ; Check if i - arr [ j ] exist in the array or not using set If yes , Then i can be represented as sum of arr [ j ] + ( i - arr [ j ] ) ; if Count is greater than 2 break the loop ; 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 = 10000 ; static Vector < Integer > arr = new Vector < Integer > ( ) ; static void ulam ( ) { Set < Integer > s = new HashSet < Integer > ( ) ; arr . add ( 1 ) ; s . add ( 1 ) ; arr . add ( 2 ) ; s . add ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) ; j ++ ) { if ( s . contains ( i - arr . get ( j ) ) && arr . get ( j ) != ( i - arr . get ( j ) ) ) count ++ ; if ( count > 2 ) break ; } if ( count == 2 ) { arr . add ( i ) ; s . add ( i ) ; } } } public static void main ( String [ ] args ) { ulam ( ) ; int n = 9 ; System . out . println ( arr . get ( n - 1 ) ) ; } }