Вызов
Учитывая положительное целое число, определите, является ли оно треугольным числом, и, соответственно, выведите одно из любых двух постоянных, различных значений.
Определение
Треугольное число является числом , которое может быть выражено в виде суммы последовательных положительных целых чисел, начиная с 1. Кроме того, они могут быть выражены с формулой n(n + 1) / 2
, где n
имеет некоторое положительное целое число.
Контрольные примеры
Truthy:
1
3
6
10
15
21
55
276
1540
2701
5050
7626
18915
71253
173166
222111
303031
307720
500500
998991
Falsy:
2
4
5
7
8
9
11
16
32
50
290
555
4576
31988
187394
501500
999999
правила
- Ваша запись может быть функцией или программой.
- Вы можете предположить, что на входе положительное целое число меньше 10 6 .
- Вы должны выбрать два постоянных, отличных выхода, чтобы различать две категории.
Это код-гольф , поэтому выигрывает самый короткий код в байтах на каждом языке.
code-golf
number
decision-problem
ETHproductions
источник
источник
Ответы:
Haskell , 23 байта
РЕДАКТИРОВАТЬ:
$
.Анонимная функция, принимающая
Int
и возвращающаяChar
.Output is
'1'
for triangular numbers and'0'
for others.Try it online!
((!!)$show.(10^)=<<[0..]) 998991
.Generates the numbers 1, 10, 100, 1000, ..., converts those to strings, and concatenates them. Then indexes into the resulting infinite string
источник
(!!)$show.(10^)=<<[0..]
.Python, 24 bytes
Try it online!
Outputs
False
for triangular numbers,True
for the rest. Checks if8*n+1
is a perfect square. Python will take perfect squares to exact integer floats no matter how large, so there are no floating-point issues.источник
(1<<10000)**.5
: OverflowError: int too large to convert to floatJelly, 4 bytes
Try it online!
How?
источник
/
and\
probably were among the first five quicks to be implemented, predating the idea to cast integer arguments to range.Retina, 10 bytes
Input is in unary. Output is
0
or1
.Try it online! (As a test suite that does decimal-to-unary conversion for convenience.)
Explanation
This is the most basic exercise in forward-references. Most people are familiar with backreferences in regex, e.g.
(.)\1
to match a repeated character. However, some of the more advanced flavours allow you to use a backreference before or inside the group it's referring to. In that case, it's usually called a forward-reference. This can make sense if the reference is repeated. It might not be well defined on the first iteration, but on subsequent iterations, the later or surrounding group has captured something and can be reused.This is most commonly used to implement recurrent patterns on unary strings. In this case, we try to match the input as the sum of consecutive integers:
источник
(^|1\1)+$
work?+
to{2,}
, it should work. This optimisation prevents infinite loops but it's also the only thing that keeps .NET regex from being Turing-complete on its own.\G
!Python 2, 25 bytes
Checks if (8x+1) is a square number.
Try it online!
источник
Mathematica, 16 bytes
Essentially a port of xnor's Python solution. Outputs
True
for triangular numbers,False
otherwise.источник
JavaScript (ES6),
3027 bytesSaved 2 bytes thanks to kamoroso94
Test cases
Show code snippet
Non-recursive version (ES7), 19 bytes
Port of Adnan's answer.
источник
f=(n,k=1)=>n>0?f(n-k,k+1):!n
?k
.undefined
value; your edit was a pleasure to read after I independently arrived at your prior solution.CJam, 11 bytes
Outputs
1
for triangular,0
otherwise.Try it online!
Explanation
Consider input
21
.источник
Brain-Flak, 40 bytes
Wheat Wizard and I had a duel over this question. When we decided to post our solutions we were tied at 42 bytes, but I found a 2 byte golf of his solution. We decided that would count as the tie breaker (my solution is below).
Try it online!
Explanation:
For a full explanation please see Wheat Wizard's answer.
Brain-Flak, 42 bytes
Outputs
0\n
(literal newline) for truthy, and the empty string for falsy.The idea is to subtract 1 then 2 then 3 all the way up to the input. If you hit 0, then you know this is a triangular number, so you can stop there.
Try it online! (truthy)
Try it online! (falsy)
Here's a 46 byte solution that I found interesting.
Outputs
0\n
(literal newline) for truthy, the empty string for falsy.The idea is to count down from input by consecutive numbers, 1 at a time. E.g.
input - (1) - (1,1) - (1,1,1)
. Each time we subtract, if we aren't at 0 yet, we leave an extra value on the stack. That way, if we are at 0 and are still subtracting when we pop we remove the last value on the stack. If the input was a triangular number, we will end exactly at 0, and wont pop the 0.Try it online! truthy
Try it online! falsy
источник
Jelly, 5 bytes
Try it online!
Background
Let n be the input. If n is the kth triangular number, we have
which means there will be a natural solution if and only if 1 + 8n is an odd, perfect square. Clearly, checking the parity of 1 + 8n is not required.
How it works
источник
PowerShell,
3130 bytesTry it online!
Nice and slow brute force method. Make an array of every sum of 1 through 106, and see if the argument is in there.
источник
Brain-Flak, 42 bytes
Try it online!
Explanation
The goal of this program is to create a state on two stacks and perform constant operation on both stacks until one of them zeros, we can then output depending on which stack we are on. This is similar to programs that determine the sign of a number. These programs put
n
on one stack and-n
on the other and add one and switch stacks until one of the stacks is zero. If the number was negative in the first place the first stack will hit zero, if the number was positive the other stack will hit zero.Here we create two stacks one that subtracts consecutive numbers from the input and one that just subtracts one. The one that subtracts consecutive numbers will only terminate if the number is triangular, (other wise it will just pass zero and keep going into the negatives). The other one will always terminate for any positive number, but will always do so slower than the first, thus non-triangular numbers will terminate on that stack.
So how do we set up stacks so that the same operation subtracts consecutive numbers on one and subtracts one on the other? On each stack we have the input on top so that in can be checked, below that we have the difference and below that we have the difference of the difference. Each time we run we add the "difference of the difference" to the regular "difference" and subtract that from the input. For the stack that checks for triangularity we set our double difference to be
1
so that we get consecutive integers each time we run, for the other stack we set it to0
so that we never change the difference, that is it always stays 1. Here is how the stack is set up at the beginning, wheren
is the input:When we finally do terminate we can use these differences to check which stack we are on we pop the top two values and we get
1
for a triangular number and0
for a non-triangular number.Annotated code
Here's a 50 byte solution I like as well.
Try it online!
источник
Cubix, 23
2425bytes0 for truthy and nothing
0for falsey. Brutes forces by incrementing counter, adding to cumulative sum and comparing to input.Now to try and fit it on a 2x2x2 cube.Did it!Try it online!
/
Reflect to to face.I10\
get integer input, push 1 (counter), push 0 (sum) and reflect+s;p-
loop body. Add sum and counter, drop previous sum, raise input and subtract?
Test the result of the subtraction\.uO@
reflect to bottom face, no-op, U-turn, output and halt.@
halt;qWs)/su
drop subtraction, put input to bottom, shift left, swap counter and sum, increment counter, reflect, swap sum and counter, U-turn onto main loop body.источник
.
on the cube but a1
in your code.05AB1E,
76 bytesEDIT: Thanks to @Dennis: Saved a byte because I forgot about the increment operator
Try it online!
n
is triangular ifsqrt(8n + 1)
is an integerHow it works
источник
t.ï
can beŲ
these days, which is a builtin to check if a number is a square.Perl 6, 17 bytes
Just checks whether
$_
, the input to the function, is equal to any of the elements of the triangular addition reduction(1, 1+2, ..., 1+2+...+$_)
.источник
Alice,
3822 bytesA lot of bytes saved thanks to Martin and Leo
There is a trailing newline. Outputs
1
for triangular,0
otherwise.Try it online!
Explanation
This uses the same approach as my CJam answer, only clumsier. In linearized form, the program becomes
where the
i
ando
are actually in ordinal mode.Consider input
21
as an example.источник
...h*-no@
)Japt,
107 bytesSaved 3 bytes thanks to @Luke and @ETHproductions
Try it online!
Explanation:
Explanation:
Try it online!
источник
*8Ä ¬u1 c
for 9B (outputs 0 if input is triangular, 1 otherwise)u1 c
tov1
, I believe (switching the outputs)R,
2319 bytesSimilar approach as other answers. Checks to see if
8x+1
is a perfect square.-4 bytes thanks Giuseppe and MickyT.
Try it online!
источник
!
instead of==0
!(8*scan()+1)^.5%%1
MATL, 5 bytes
Try it online!
Explanation:
источник
t:Ys=a
. Forgot aboutm
:-)m
until I saw this answer. Funny how the two answer are almost identical :DBatch, 72 bytes
Outputs 1 on success, nothing on failure. Works for zero too, although not requested by the question for some reason.
источник
JavaScript (ES7),
1918 bytesFrom my answer to a related question.
Outputs
false
for triangular numbers ortrue
for non-triangular, as permitted by the OP.Try It
источник
n=>(8*n+1)**.5%1>0
(which would reverse the outputs)PHP, 30 Bytes
Prints 1 for true and nothing for false
Try it online!
fmod
PHP, 37 Bytes
Prints 1 for true and nothing for false
Try it online!
источник
Mathematica, 28 bytes
источник
7!
by#
. First, it's shorter; more importantly, the current solution is not correct, as it artificially imposes a limit on the size of the input it works on.Pari/GP, 18 bytes
Try it online!
There is a built-in to test if a number is a polygonal number, but it is one byte longer.
Pari/GP, 19 bytes
Try it online!
источник
Excel,
3122 bytes9 bytes saved thanks to Octopus
Outputs
TRUE
for triangular numbers. ElseFALSE
. Checks if8*n+1
is a perfect square.источник
=MOD(SQRT(8*A1+1),1)=0
saves a few bytesBrachylog, 5 bytes
Try it online!
Explanation
источник
Fourier, 26 bytes
Try it online!
источник
Python - 52 bytes
Note: I know that the other two Python answers are much shorter, but this is the old-school way, more of a by-hand algorithm
источник
APL (Dyalog), 6 bytes
Try it online!
Explanation
Outputs
0
for false and1
for true.источник
TI-BASIC,
107 bytes-3 thanks to @lirtosiast
Takes input on
X
. Checks if√(8X+1)
is a whole numberисточник
not(fPart(√(8Ans+1
?