Ulam Number Sequence | Python3 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
MAX = 10000 NEW_LINE arr = [ ] NEW_LINE def ulam ( ) : NEW_LINE INDENT s = set ( ) NEW_LINE arr . append ( 1 ) NEW_LINE s . add ( 1 ) NEW_LINE arr . append ( 2 ) NEW_LINE s . add ( 2 ) NEW_LINE for i in range ( 3 , MAX ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( i - arr [ j ] ) in s and arr [ j ] != ( i - arr [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if count > 2 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if count == 2 : NEW_LINE INDENT arr . append ( i ) NEW_LINE s . add ( i ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ulam ( ) NEW_LINE n = 9 NEW_LINE print ( arr [ n - 1 ] ) NEW_LINE DEDENT