Ulam Number Sequence | C # 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
using System ; using System . Collections . Generic ; class GFG { static readonly int MAX = 10000 ; static List < int > arr = new List < int > ( ) ; static void ulam ( ) { HashSet < int > s = new HashSet < int > ( ) ; 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 . Count ; j ++ ) { if ( s . Contains ( i - arr [ j ] ) && arr [ j ] != ( i - arr [ 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 ; Console . WriteLine ( arr [ n - 1 ] ) ; } }