Earn extra honor and gain new allies!
Honor is earned for each new codewarrior who joins.
Learn more
Code
Diff
  • def mul():
        return sum([i for i in range(1000) if i%3 == 0 or i%5 == 0])
        
  • 11
    def mul():
    
    2
        sum=0
    
    3
        for i in range(1, 1000):
    
    4
            if(i % 3 == 0 or i % 5 == 0):
    
    5
                sum += i
    
    6
        return sum
    
    2+
        return sum([i for i in range(1000) if i%3 == 0 or i%5 == 0])
    
    77
        
    
Puzzles
Games
Sequences
Arrays
Arithmetic
Mathematics
Algorithms
Numbers
Recursion
Computability Theory
Theoretical Computer Science

The Ulam Sequence is a recursive sequence that begins with two numbers; for example [1, 2]. The next number in the sequence is the smallest unique sum of any 2 numbers in the sequence.

Example:
[u0, u1] = [1, 2]
u2 = 1 + 2 = 3 --> [1, 2, 3]
u3 = 1 + 3 = 4 --> [1, 2, 3, 4]
u4 = 4 + 2 = 6 --> [1, 2, 3, 4, 6]

Notice that 5 is left out. Though 5 is smaller than 6, 5 can be written as a sum in 2 different ways: 4 + 1 and 3 + 2; therefore, it is not unique; whereas, 6 is unique since it is only the sum of 4 + 2.

Write a code that generates an Ulam Sequence of length n and starts with u0, u1.

Ex:
f(u0=1, u1=2, n=10) = [1, 2, 3, 4, 6, 8, 11, 13, 16, 18]

def ulam_sequence(u0, u1, n):
    u = [u0, u1]
    nn = u[-1] + 1
    while len(u) < n:
        count = 0
        for i in u:
            if nn - i in u and nn - i != i:
                count += 1
            if count >= 3:
                break
                nn += 1
        if count == 2:
            u.append(nn)
        nn += 1
    return u