前十个自然数的平方和为
前十个自然数之和的平方是
因此,前十个自然数的平方和与平方和之差为
对于给定的输入n,找到前n个自然数的平方和与和的平方之差。
测试用例
1 => 0
2 => 4
3 => 22
10 => 2640
24 => 85100
100 => 25164150
这项挑战最初是在欧拉6号项目上宣布的。
获奖标准
对于输入为负数或为零的行为,没有任何规则。
最短的答案将获胜。
n?
前十个自然数的平方和为
前十个自然数之和的平方是
因此,前十个自然数的平方和与平方和之差为
对于给定的输入n,找到前n个自然数的平方和与和的平方之差。
测试用例
1 => 0
2 => 4
3 => 22
10 => 2640
24 => 85100
100 => 25164150
这项挑战最初是在欧拉6号项目上宣布的。
对于输入为负数或为零的行为,没有任何规则。
最短的答案将获胜。
n?
Answers:
((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{})
进行一些棘手的转换非常简单。希望有人能找到更多的技巧来使它变得更短。
((×⍨+/)-(+/×⍨))⍳
(×⍨+/) The square (× self) of the sum (+ fold)
- minus
(+/×⍨) the sum of the square
( )⍳ of [1, 2, … input].
⍳内部可以节省更多的字节(×⍨1⊥⍳)-⍳+.×⍳
-4字节感谢alephalpha。
(3#+2)(#^3-#)/12&
纯功能。以整数作为输入并返回整数作为输出。由于Sums,Ranges,Trs等占用大量字节,因此仅实现多项式。
#.(#^2-#)&@*Range实现了另一个常见的解决方案。(但是它也是17个字节。)我们可以在18个字节中实现朴素算法:Tr@#^2-#.#&@*Range。
-1字节感谢Zacharý
-11字节归功于ceilingcat
宏版本:
#define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6
功能版本:
int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;}
那些行基于那2个公式:
1和n之间的数字总和= n*(n+1)/2
1和n之间的平方和=n*(n+1)*(2n+1)/6
所以得到答案的公式很简单 (n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6
现在,为了“优化”字节数,我们打破括号并四处移动,同时对其进行测试始终得出相同的结果
(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6=>
n*(n+1)/2*n*(n+1)/2 - n*(n+1)*(2n+1)/6=>
n*(n+1)*n*(n+1)/4 - n*(n+1)*(2n+1)/6
注意pattern p = n*n+1 = n*n+n,所以在函数中,我们声明了另一个变量int p = n*n+n,它给出了:
p*p/4 - p*(2n+1)/6
因为p*(p/4-(2*n+1)/6)如此n*(n+1)*(n*(n+1)/4 - (2n+1)/6),它只能工作一半时间,而且我怀疑是整数除法的原因(f(3)给出24而不是22,f(24)给出85200而不是85100,因此我们不能以这种方式分解宏的公式,即使在数学上是相同。
由于存在宏替换,因此宏和函数版本都在此处:
F(3)给出3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22
F(5-2)给出5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30
并弄乱了运算符的优先级。功能版本没有这个问题
n用(n)。另外,F(n) n=> F(n)n不管。
return p*p/4-p*(n-~n)/6为return(p/4-(n-~n)/6)*p。
(fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s))))
#(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12)
(apply +字段比短(reduce +。
b$)^2-c$
;$
;$$
b$)^2-c$ First line
: Implicit (output nth term in sequence)
b$) Each term in the sequence equals the second line at the current index
^2 squared
-c$ minus the third line at the current index
;$ Second line - sum of integers up to n
;$$ Third line - sum of squares up to n
#&àĝ&oȦ
./jael --explain '#&àĝ&oȦ'
ORIGINAL CODE: #&àĝ&oȦ
EXPANDING EXPLANATION:
à => `a
ĝ => ^g
Ȧ => .a!
EXPANDED CODE: #&`a^g&o.a!
COMPLETED CODE: #&`a^g&o.a!,
# , repeat (p1) times:
& push number of iterations of this loop
` push 1
a push p1 + p2
^ push 2
g push p2 ^ p1
& push number of iterations of this loop
o push p1 * p2
. push the value under the tape head
a push p1 + p2
! write p1 to the tapehead
␄ print machine state