Ulam Number Sequence | CPP 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 1 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 ( ) { arr . push_back ( 1 ) ; arr . push_back ( 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 [ j ] + arr [ k ] == i ) { count ++ ; } if ( count > 1 ) break ; } if ( count > 1 ) break ; } if ( count == 1 ) { arr . push_back ( i ) ; } } } int main ( ) { ulam ( ) ; int n = 9 ; cout << arr [ n - 1 ] ; return 0 ; }