Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ulam Number Sequence

  • Last Updated : 18 Aug, 2021

Given a positive integer n , the task is to print nth Number of the Ulam Number Sequence
Ulam Number: In Mathematics, An Ulam number is the member of an Integer sequence that starts with the term U1 = 1 and U1 = 2 and then for every n > 2, Un is defined is smallest positive integer greater than Un-1 which can be expressed as sum of two distinct earlier term of the sequence in exactly one way. 
For example, 
 

  • 3 is an Ulam Number as it can be expressed as sum of two distinct earlier terms in exactly one way 
    ( i.e 1 + 2 )
  • 4 is also an Ulam number. Other than ( 1 + 3) we can express 4 as ( 2 + 2 ) but in (2 + 2) terms are not distinct. So we have only one way
  • 5 can be expressed as sum of two distinct earlier terms of the sequence in two ways 
    as ( 1 + 4 ) and ( 2 + 3), So, 5 is not an Ulam Number

The first few terms of the Ulam number sequence are- 
 

1, 2, 3, 4, 6, 8, 11, 13, 16, 18, 26, 28, 36, 38, 47, 48, 53, 57, 62, 69, 72, 77, 82, 87, 97, 99, 102 
 

Examples: 
 

Input  : 5
Output : 6

Input : 9
Output : 16

 

A Simple Solution to print nth term of the Ulam number sequence is to generate entire ulam sequence up to n and print nth term, As we can not compute nth term directly. 
Approach to generate ulam number sequence: 
 

  • As, We have first two term of the sequence as U1=1 and U2=2. we can start our search from i=3 for next Ulam number.
  • For every value of ‘i’ traverse the earlier terms of the sequence using two loops and check if on adding two distinct term of sequence we can get sum as i in exactly one way or not
  • If Yes, Then ‘i’ is next Ulam number, Store it. and then search for next ulam number
  • If not, then increment ‘i’ and repeat the same
  • Keep searching ulam number, until we get our nth term

Below is the implementation of the above idea: 
 

C++




// CPP code to print nth
// Ulam number
 
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 10000
 
// Array to store Ulam Number
vector<int> arr;
 
// function to compute ulam Number
void ulam()
{
    // push First 2 two term of the sequence
    // in the array
    // for further calculation
 
    arr.push_back(1);
 
    arr.push_back(2);
 
    // loop to generate Ulam number
    for (int i = 3; i < MAX; i++) {
 
        int count = 0;
 
        // traverse the array and check if
        // i can be represented as sum of
        // two distinct element of the array
 
        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 is 1 that means
        // i can be represented as sum of
        // two distinct terms of the sequence
 
        if (count == 1) {
            // i is ulam number
            arr.push_back(i);
        }
    }
}
 
// Driver code
int main()
{
    // Pre compute Ulam Number sequence
    ulam();
 
    int n = 9;
 
    // Print nth Ulam number
    cout << arr[n - 1];
 
    return 0;
}

Java




// JAVA code to print nth
// Ulam number
 
import java.util.*;
class GFG {
 
    static final int MAX = 1000;
 
    // Array to store Ulam Number
    static Vector<Integer> arr = new Vector<Integer>();
 
    // Function to compute ulam Number
    static void ulam()
    {
 
        // push First 2 two term of the sequence
        // in the array
        // for further calculation
 
        arr.add(1);
 
        arr.add(2);
 
        // loop to generate Ulam number
        for (int i = 3; i < MAX; i++) {
 
            int count = 0;
 
            // traverse the array and check if
            // i can be represented as sum of
            // two distinct element of the array
 
            for (int j = 0; j < arr.size() - 1; j++) {
 
                for (int k = j + 1; k < arr.size(); k++) {
 
                    if (arr.get(j) + arr.get(k) == i) {
 
                        count++;
                    }
                    if (count > 1)
                        break;
                }
                if (count > 1)
                    break;
            }
 
            // If count is 2 that means
            // i can be represented as sum of
            // two distinct terms of the sequence
 
            if (count == 1) {
                // i is ulam number
                arr.add(i);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // pre compute Ulam Number sequence
        ulam();
 
        int n = 9;
 
        // print nth Ulam number
        System.out.println(arr.get(n - 1));
    }
}

Python3




# Python3 code to print nth
# Ulam number
MAX = 1000
 
# Array to store Ulam Number
arr = []
 
# function to compute ulam Number
def ulam():
 
    # push First 2 two term of the sequence
    # in the array
    # for further calculation
    arr.append(1);
    arr.append(2);
 
    # loop to generate Ulam number
    for i in range(3, MAX):
        count = 0;
 
        # traverse the array and check if
        # i can be represented as sum of
        # two distinct element of the array
        for j in range(len(arr) - 1):
            for k in range(j + 1, len(arr)):
                if (arr[j] + arr[k] == i):
                    count += 1
                if (count > 1):
                    break;           
            if (count > 1):
                break;
         
        # If count is 1 that means
        # i can be represented as sum of
        # two distinct terms of the sequence
        if (count == 1):
           
            # i is ulam number
            arr.append(i);
         
# Driver code
if __name__=='__main__':
 
    # Pre compute Ulam Number sequence
    ulam();
    n = 9;
 
    # Print nth Ulam number
    print(arr[n - 1])
 
# This code is contributed by rutvik_56.

C#




// C# code to print nth
// Ulam number
using System;
using System.Collections.Generic;
 
class GFG
{
    static readonly int MAX = 1000;
 
    // Array to store Ulam Number
    static List<int> arr = new List<int>();
 
    // Function to compute ulam Number
    static void ulam()
    {
 
        // push First 2 two term of 
        // the sequence in the array
        // for further calculation
 
        arr.Add(1);
        arr.Add(2);
 
        // loop to generate Ulam number
        for (int i = 3; i < MAX; i++)
        {
            int count = 0;
 
            // traverse the array and check if
            // i can be represented as sum of
            // two distinct element of the array
            for (int j = 0; j < arr.Count - 1; j++)
            {
 
                for (int k = j + 1; k < arr.Count; k++)
                {
                    if (arr[j] + arr[k] == i)
                    {
                        count++;
                    }
                    if (count > 1)
                        break;
                }
                if (count > 1)
                    break;
            }
 
            // If count is 2 that means
            // i can be represented as sum of
            // two distinct terms of the sequence
            if (count == 1)
            {
                // i is ulam number
                arr.Add(i);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // pre compute Ulam Number sequence
        ulam();
 
        int n = 9;
 
        // print nth Ulam number
        Console.WriteLine(arr[n - 1]);
    }
}
 
// This code is contributed by Rajput-JI

Javascript




<script>
// Javascript code to print nth
// Ulam number
 
var MAX = 10000;
 
// Array to store Ulam Number
var arr = [];
 
// function to compute ulam Number
function ulam()
{
    // push First 2 two term of the sequence
    // in the array
    // for further calculation
    arr.push(1);
    arr.push(2);
 
    // loop to generate Ulam number
    for (var i = 3; i < MAX; i++) {
 
        var count = 0;
 
        // traverse the array and check if
        // i can be represented as sum of
        // two distinct element of the array
 
        for (var j = 0; j < arr.length - 1; j++) {
 
            for (var k = j + 1; k < arr.length; k++) {
 
                if (arr[j] + arr[k] == i) {
 
                    count++;
                }
                if (count > 1)
                    break;
            }
            if (count > 1)
                break;
        }
 
        // If count is 1 that means
        // i can be represented as sum of
        // two distinct terms of the sequence
 
        if (count == 1)
        {
         
            // i is ulam number
            arr.push(i);
        }
    }
}
 
// Driver code
// Pre compute Ulam Number sequence
ulam();
var n = 9;
 
// Print nth Ulam number
document.write( arr[n - 1]);
 
// This code is contributed by noob2000.
</script>
Output: 
16

 

An Efficient solution is to use a hash table to store the earlier number of the sequence so that instead of using two loops to check if ‘i’ can be expressed as the sum of two distinct terms in exactly one way or not, we can do it in a single loop. Searching will be fast if we will use a hash table. 
Below is the Implementation of above idea: 
 

C++




// Cpp code to print nth
// Ulam number
 
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 10000
 
// Array to store Ulam Number
vector<int> arr;
 
// function to compute ulam Number
void ulam()
{
 
    // Set to search specific Ulam number efficiently
    unordered_set<int> s;
 
    // push First 2 two term of the sequence
    // in the array and set
    // for further calculation
 
    arr.push_back(1);
    s.insert(1);
 
    arr.push_back(2);
    s.insert(2);
 
    // loop to generate Ulam number
    for (int i = 3; i < MAX; i++) {
 
        int count = 0;
 
        // traverse the array and check if
        // i can be represented as sum of
        // two distinct element of the array
 
        for (int j = 0; j < arr.size(); j++) {
 
            // 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 (s.find(i - arr[j]) != s.end() && arr[j] != (i - arr[j]))
                count++;
 
            // if Count is greater than 2
            // break the loop
            if (count > 2)
                break;
        }
 
        // If count is 2 that means
        // i can be represented as sum of
        // two distinct terms of the sequence
 
        if (count == 2) {
            // i is ulam number
            arr.push_back(i);
            s.insert(i);
        }
    }
}
 
// Driver code
int main()
{
    // pre compute Ulam Number sequence
    ulam();
 
    int n = 9;
 
    // print nth Ulam number
    cout << arr[n - 1];
 
    return 0;
}

Java




// JAVA code to print nth
// Ulam number
 
import java.util.*;
class GFG {
 
    static final int MAX = 10000;
 
    // Array to store Ulam Number
    static Vector<Integer> arr = new Vector<Integer>();
 
    // function to compute ulam Number
    static void ulam()
    {
 
        // Set to search specific Ulam number efficiently
        Set<Integer> s = new HashSet<Integer>();
 
        // push First 2 two term of the sequence
        // in the array and set
        // for further calculation
 
        arr.add(1);
        s.add(1);
 
        arr.add(2);
        s.add(2);
 
        // loop to generate Ulam number
        for (int i = 3; i < MAX; i++) {
 
            int count = 0;
 
            // traverse the array and check if
            // i can be represented as sum of
            // two distinct element of the array
 
            for (int j = 0; j < arr.size(); j++) {
 
                // 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 (s.contains(i - arr.get(j)) && arr.get(j) != (i - arr.get(j)))
                    count++;
 
                // if Count is greater than 2
                // break the loop
                if (count > 2)
                    break;
            }
 
            // If count is 2 that means
            // i can be represented as sum of
            // two distinct terms of the sequence
 
            if (count == 2) {
                // i is ulam number
                arr.add(i);
                s.add(i);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // pre compute Ulam Number sequence
        ulam();
 
        int n = 9;
 
        // print nth Ulam number
        System.out.println(arr.get(n - 1));
    }
}

Python3




# Python3 code to print nth Ulam number
MAX = 10000
 
# Array to store Ulam Number
arr = []
 
# function to compute ulam Number
def ulam():
 
    # Set to search specific Ulam
    # number efficiently
    s = set()
 
    # push First 2 two term of the
    # sequence in the array and set
    # for further calculation
    arr.append(1)
    s.add(1)
 
    arr.append(2)
    s.add(2)
 
    # loop to generate Ulam number
    for i in range(3, MAX):
 
        count = 0
 
        # traverse the array and check if
        # i can be represented as sum of
        # two distinct element of the array
        for j in range(0, len(arr)):
 
            # 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 (i - arr[j]) in s and arr[j] != (i - arr[j]):
                count += 1
 
            # if Count is greater than 2
            # break the loop
            if count > 2:
                break
         
        # If count is 2 that means
        # i can be represented as sum of
        # two distinct terms of the sequence
        if count == 2:
            # i is ulam number
            arr.append(i)
            s.add(i)
         
# Driver Code   
if __name__ == "__main__":
 
    # pre compute Ulam Number sequence
    ulam()
 
    n = 9
 
    # print nth Ulam number
    print(arr[n - 1])
 
# This code is contributed by Rituraj Jain

C#




// C# code to print nth
// Ulam number
using System;
using System.Collections.Generic;
 
class GFG
{
 
    static readonly int MAX = 10000;
 
    // Array to store Ulam Number
    static List<int> arr = new List<int>();
 
    // function to compute ulam Number
    static void ulam()
    {
 
        // Set to search specific Ulam number efficiently
        HashSet<int> s = new HashSet<int>();
 
        // push First 2 two term of the sequence
        // in the array and set
        // for further calculation
        arr.Add(1);
        s.Add(1);
 
        arr.Add(2);
        s.Add(2);
 
        // loop to generate Ulam number
        for (int i = 3; i < MAX; i++)
        {
 
            int count = 0;
 
            // traverse the array and check if
            // i can be represented as sum of
            // two distinct element of the array
 
            for (int j = 0; j < arr.Count; j++)
            {
 
                // 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 (s.Contains(i - arr[j]) &&
                    arr[j] != (i - arr[j]))
                    count++;
 
                // if Count is greater than 2
                // break the loop
                if (count > 2)
                    break;
            }
 
            // If count is 2 that means
            // i can be represented as sum of
            // two distinct terms of the sequence
            if (count == 2)
            {
                // i is ulam number
                arr.Add(i);
                s.Add(i);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // pre compute Ulam Number sequence
        ulam();
 
        int n = 9;
 
        // print nth Ulam number
        Console.WriteLine(arr[n - 1]);
    }
}
 
// This code is contributed by Rajput-Ji
Output: 
16

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!