C++ Program to Generate a Sequence of Ulam Numbers

This C++ Program which generates a sequence of ulam numbers. Ulam number is defined to be the smallest integer that is the sum of two distinct earlier terms in exactly one way. The program uses 1 and 2 as the first two terms and the other terms are generated on the basis of definition of ulam numbers and stored in a vector.

Here is source code of the C++ program which generates a sequence of ulam numbers. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Generate Sequence of Ulam Numbers
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int uterm1 = 1, uterm2 = 2, num = 0;
  11.     vector<int> v;
  12.  
  13.     v.push_back(1);
  14.     num++;
  15.     v.push_back(2);
  16.     num++;
  17.     for (int i = 3; i <= 100; i++)
  18.     {
  19.         int count = 0;
  20.         for (int j = 0; j < num; j++)
  21.         {
  22.              for (int k = j + 1; k < num; k++)
  23.              {
  24.                  if (v[j] + v[k] == i)
  25.                	     count++; 
  26.              }
  27.         }
  28.         if (count == 1){
  29.             v.push_back(i);
  30.             num++;
  31.         }
  32.     }
  33.     cout << "The sequence of ulam numbers is as follows : " << endl;
  34.     for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
  35.         cout << *i << '\t';  
  36.     cout << endl;
  37. }

$ g++ main.cpp
$ ./a.out
The sequence of ulam numbers is as follows : 
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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.