简体   繁体   中英

Find number in Ulam Sequence C

I want to be able to create the Ulam number sequence and be able to find the nth Ulam number. For example, if your input is "8" the output should be 13. If the input is 700, the output should be the 700th Ulam number (don't know what it is exactly). The first two numbers are 1 and 2.

I imagine I need an array initialized to 1 and 2 and use a double loop to get the next number by checking if the next number is the minimum possible value with a unique representation.

Im just not sure how to code this in C. However even pseudo code would help me figure this out. Any help is appreciated.

An Ulam number in the Ulam sequence must be representable in only one way as a sum of its two predecessors.

Note that the two predecessors are not "independent" - if you choose one, then you can calculate the second.

Example: the sequence starts with the numbers 1, 2, 3, 4, 6, 8, 11, 13, 16, 18.

Is eg 21 the next number? Start checking all previous numbers like so:

  • Suppose one of the elements of the sum is 1 . Then 1 + x = 21 . For here, x = 21 - 1 = 20 . Is 20 an element of the sequence? No.
  • Suppose one of the elements of the sum is 2 . Then 2 + x = 21 . For here, x = 21 - 2 = 19 . Is 19 an element of the sequence? No.
  • Suppose one of the elements of the sum is 3 . Then 3 + x = 21 . For here, x = 21 - 3 = 18 . Is 18 an element of the sequence? Yes => we found one representation: 21 = 3 + 18 .
  • Suppose one of the elements of the sum is 4 . Then 4 + x = 21 . For here, x = 21 - 4 = 17 . Is 17 an element of the sequence? No.
  • Suppose one of the elements of the sum is 6 . Then 6 + x = 21 . For here, x = 21 - 6 = 15 . Is 15 an element of the sequence? No.
  • Suppose one of the elements of the sum is 8 . Then 8 + x = 21 . For here, x = 21 - 8 = 13 . Is 13 an element of the sequence? Yes => we found another representation: 21 = 8 + 13 , so 21 is not a member of the sequence.

So, to check whether a number is a member of the sequence, you need to check all its predecessors.

If you check all numbers in the manner described, you will discover all members of the sequence one by one. Stop when arrived to the needed index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM