Ulam Number Sequence | Cpp 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  10000 NEW_LINE vector < int > arr ; void ulam ( ) { unordered_set < int > s ; arr . push_back ( 1 ) ; s . insert ( 1 ) ; arr . push_back ( 2 ) ; s . insert ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) ; j ++ ) { if ( s . find ( i - arr [ j ] ) != s . end ( ) && arr [ j ] != ( i - arr [ j ] ) ) count ++ ; if ( count > 2 ) break ; } if ( count == 2 ) { arr . push_back ( i ) ; s . insert ( i ) ; } } } int main ( ) { ulam ( ) ; int n = 9 ; cout << arr [ n - 1 ] ; return 0 ; }