Is it in the sequence? (sum of the first n cubes)
According to Nicomachus' theorem, the sum of the first n cubes is equal to the square of the nth triangular number. See this question for a visualisation.
Your task today is to take an integer and determine if it is in the sequence of the sum of the first n cubes.
I take the opportunity to say Happy New Year for 2025! because 2025 is the 9th number in this sequence:
Input
An integer greater than zero. Your answer should be able to handle inputs at least up to 2^31-1 unless your language's maximum type size does not support this.
Output
Either of two distinct values: one if the number is in the sequence, another if it isn't.
Try it online!
Attempt This Online!
Explanation:
The nth square triangle number is \$x = (\frac{n(n+1)}{2})^2\$, so \$2\sqrt{x}=n^2+n\$, giving \$n=\frac{-1+\sqrt{1+8\sqrt{x}}}{2}\$. Since \$n\$ has to be an integer, that means \$\sqrt{1+8\sqrt{x}}\$ has to be an odd integer, i.e., \${\sqrt{1+8\sqrt{x}}}\mod{2}=1\$.
Try it
Pad
-1 byte: Tbw - switched from checking \$n\in \sum k^3\$ to \$\sqrt{n}\in \sum k\$
Creates a list of \$\sum_{k=0}^n k \ (0\le n\le 999)\$, then checks membership of \$\sqrt{n}\$. Since the largest squared triangular number under \$2^{31}-1\$ is the \$303^{\text{st}}\$, this range must be 3 digits so we go up to the \$999^{\text{th}}\$.
Try it online!
Try it online!
Edit
-3 thanks to att to shorten Sqrt
Try it online! Link includes some test cases. Explanation: Converts the input to unary, then searches for a triangular number whose square is the input.
Prompts for integer.
Try it online! Thanks to Dyalog Classic
Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. - for a sum of cubes, nothing if not. Explanation: Port of my golf to @V_R's Python answer.
If potential floating-point accuracy is acceptable, then for 10 bytes:
Try it online! Link is to verbose version of code. Explanation: Port of @Eonema's R answer.
Try it online!
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a 32-bit integer in EDI and returns a 32-bit integer in EAX, which is 0 if the number is in the sequence and -1 if it is not.
In assembly:
-1 thanks to Neil
Takes quite a long time for inputs like 2^31-1...
Try it online!
The xth triangular number is (x*x+x)/2, and we're looking for the square of that: ((x*x+x)/2)**2
We can save two characters by squaring the numerator and denominator separately: (x*x+x)**2/4
We need range(n+1) instead of range(n) to return True when n is 1
Expects the integer in cell A1. Returns true or false.
See A000537. Thanks to Arnauld.
Try it online!
This is Arnauld's code, I'm just the messenger. Posting because of lack of a JavaScript answer.