Length of a Sumac Sequence
Heavily based on this closed challenge from SE.
Description
A Sumac sequence starts with two non-zero integers $t_1$ and $t_2.$
The next term, $t_3 = t_1 - t_2$
More generally, $t_n = t_{n-2} - t_{n-1}$
The sequence ends when $t_n ≤ 0$. All values in the sequence must be positive.
Challenge
Given two integers $t_1$ and $t_2$, compute the Sumac sequence, and output it's length.
If there is a negative number in the input, remove everything after it, and compute the length.
You may take the input in any way (Array, two numbers, etc.)
Test Cases
(Sequence is included for clarification)
[t1,t2] Sequence n
------------------------------
[120,71] [120,71,49,22,27] 5
[101,42] [101,42,59] 3
[500,499] [500,499,1,498] 4
[387,1] [387,1,386] 3
[3,-128] [3] 1
[-2,3] [] 0
[3,2] [3,2,1,1] 4
Scoring
This is [tag: code-golf]. Shortest answer in each language wins.
[Python 3], 49 47 44 35 bytes …
3mo ago
[C (gcc)], 32 bytes …
5mo ago
Japt `-N`, 9 bytes ¨T©Ò …
5mo ago
[Raku], 19 bytes {( …
5mo ago
[JavaScript (Node.js)], 27 25 …
5mo ago
[Jelly], 9 bytes Rȧ@Rп …
3mo ago
[JavaScript (Node.js)], 31 byt …
5mo ago
7 answers
Python 3, 49 47 44 35 bytes
a=lambda x,y:+(x>=0)and(1+a(y,x-y))
-3 bytes thanks to @Hakerh400
-9 bytes thanks to @Jo King
Python 2, 50 bytes
x,y=input()
a=0
while x>0:x,y,a=y,x-y,a+1
print(a)
An alternate solution I also came up with that I swear I should be able to make shorter, but can't think of it currently.
JavaScript (Node.js), 27 25 bytes
(-2 thanks to JoKing)
f=(a,b)=>a<0?0:1+f(b,a-b)
1 comment
@JoKing oh right, I don't
Raku, 19 bytes
{(|@_,*-*...0>*)-1}
{ } # Anonymous code block
... # Create a sequence
|@_ # Starting with the input
,*-* # With each element being the difference between the previous two
0>* # Until it is negative
( )-1 # And return the length of the list minus one
0 comments
Jelly, 9 bytes
Rȧ[email protected]п@L
Takes $t_1$ on the left and $t_2$ on the right. R}ȧ[email protected]пL
works given the arguments in the opposite order.
R Ascending range from 1 to t_1 (truthy if positive),
ȧ and:
п collecting intermediate results, loop while
R positive
@ on the reversed arguments:
_ subtract
@ the first from the second.
L Return the length of the conjunction.
¿
and family, given a dyad, replace the right argument with the previous left argument on each successive iteration. This is incredibly bothersome for some tasks, but perfect for working with this exact kind of sequence.
4 comments
What should be the result for t1=t2=0? — celtschk 5 months ago
@celtschk sequence ends when tn is ≤ 0, so it should be 0. — Razetime 5 months ago
@Razetime: You should probably add that as a test case, as several currently posted solutions fail in this case. — celtschk 5 months ago
ok, added it in. — Razetime 5 months ago