Finding nth number of a sequence.

closed account (S6MNwA7f)
Hi,

I have to write a program to find the nth number of the Ulam numbers.

It's a bit complicated to explain what an Ulam number is but Wolfram explains it very well here:

http://mathworld.wolfram.com/UlamSequence.html

I have to find the nth Ulam number but I don't know what I have to do to get that. My program gives me all the Ulam numbers from a range of 0 to n.

What I want the program to do is tell me that the 49th Ulam number is 243.

Thanks for the help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 /* 
 C++ Program to find nth Ulam Number
 */
#include <stdio.h>
#include <iostream>
#include <vector>

using namespace std;

int main() 
{
    int num = 0;
    vector<int> v;
    
    cout << "Enter the nth number to find, e.g 5,: ";
    cin >> num;
    
    v.push_back(1);
    num++;
    v.push_back(2);
    num++;
    for (int i = 3; i <= num; i++)
    {
        int count = 0;
        for (int Ulam1 = 0; Ulam1 < num; Ulam1++)
        {
            for (int Ulam2 = Ulam1 + 1; Ulam2 < num; Ulam2++)
            {
                if (v[Ulam1] + v[Ulam2] == i)
                    count++;
            }
        }
        if (count == 1){
            v.push_back(i);
            num++;
        }
    }
    
    cout << "The Ulam number is : " << endl;
    for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
        cout << *i << '\t';
    cout << endl;
}
You are mixing value and index.

The variable num is the index+1 of the value you want to print in your list of Ulam numbers. You should not be changing it.

Line 22 should be a loop that terminates when you have a big enough list -- that is, when you have num Ulam numbers in your vector.

Don't forget you still need that i to exist and to increment every iteration of your loop.

Good luck.
closed account (S6MNwA7f)
I don't quite understand what you mean. I don't want to print the list of Ulam Numbers.

I want the user to type the specific Ulam number they want (e.g. the 50th number in the sequence) and the program to say "X is the 50th ulam number"

In the program though, it lists all the Ulam numbers below 50 which is not the same.
Last edited on
So then you either have a formula to find the nth term of the sequence, or, you do a loop and up until n and then print n, which is a slight modification of the loop given.
I don't there's much more we can say to help. Perhaps if he had done his own homework to begin with, instead of snagging someone else's code that he doesn't understand.
Topic archived. No new replies allowed.