平方和差


15

前十个自然数的平方和为 12+22++102=385

前十个自然数之和的平方是

(1+2+...+10)2=552=3025

因此,前十个自然数的平方和与平方和之差为

3025385=2640

对于给定的输入n,找到前n个自然数的平方和与和的平方之差。

测试用例

1       => 0
2       => 4
3       => 22
10      => 2640
24      => 85100
100     => 25164150

这项挑战最初是在欧拉6号项目上宣布的。

获奖标准

  • 对于输入为负数或为零的行为,没有任何规则。

  • 最短的答案将获胜。


4
这项挑战需要一个获胜的标准(例如打高尔夫球)
dylnan

2
这是问题的子集
Caird coinheringaahing

1
序列可以索引为0吗?即自然数最多n
Jo King


3
@Enigma我真的不认为这是目标的重复,因为这里的许多答案都不容易移植为答案,因此这增加了一些东西。
乔纳森·艾伦

Answers:


10

果冻 5  4 字节

Ḋ²ḋṖ

在线尝试!

怎么样?

实现 i=2n(i2(i1)) ...

Ḋ²ḋṖ - Link: non-negative integer, n
Ḋ    - dequeue (implicit range)       [2,3,4,5,...,n]
 ²   - square (vectorises)            [4,9,16,25,...,n*n]
   Ṗ - pop (implicit range)           [1,2,3,4,...,n-1]
  ḋ  - dot product                    4*1+9*2+16*3+25*4+...+n*n*(n-1)


8

APL(Dyalog Unicode),10个字节

1⊥⍳×⍳×1-⍨⍳

在线尝试!

怎么运行的

1⊥⍳×⍳×1-⍨⍳
  ⍳×⍳×1-⍨⍳  Compute (x^3 - x^2) for 1..n
1          Sum

使用“和的平方”等于“立方体的和”的事实。


对我来说1⊥⍳×⍳×1-⍨⍳不是函数;我尝试了1⊥⍳×⍳×1-⍨⍳10,但对我来说却没有编译...
RosLuP

1
@RosLuP您必须首先将其分配给变量(就像我在TIO链接中所做的那样),或者将其包装在一对括号内,例如(1⊥⍳×⍳×1-⍨⍳)10
Bubbler

7

TI-Basic(TI-83系列),12 11字节

sum(Ans² nCr 2/{2,3Ans

机具(n22)(12+13n)。接受输入Ans:例如,运行10:prgmX以计算输入的结果10


很好用nCr
林恩

6

Brain-Flak74 72 68 64字节

((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{})

在线尝试!

进行一些棘手的转换非常简单。希望有人能找到更多的技巧来使它变得更短。


5

木炭12 10字节

IΣEN×ιX⊕ι²

在线尝试!链接是详细版本的代码。说明:(1nx)2=1nx3 so (1nx)21nx2=1n(x3x2)=1n(x1)x2=0n1x(x+1)2

   N        Input number
  E         Map over implicit range i.e. 0 .. n - 1
        ι   Current value
       ⊕    Incremented
         ²  Literal 2
      X     Power
     ι      Current value
    ×       Multiply
 Σ          Sum
I           Cast to string
            Implicitly print


4

Japt -x9 8 5 4字节

õ²í*

尝试一下


说明

õ        :Range [1,input]
 ²       :Square each
  í      :Interleave with 0-based indices
   *     :Reduce each pair by multiplication
         :Implicit output of the sum of the resulting array


3

APL(Dyalog),17个字节

{+/(¯1↓⍵)×1↓×⍨⍵}⍳

(更长的时间)乔纳森·艾伦的果冻港。

在线尝试!


去默契并结合滴:+/¯1↓⍳×1⌽⍳×⍳
亚当


3

Mathematica,21个 17字节

-4字节感谢alephalpha

(3#+2)(#^3-#)/12&

纯功能。以整数作为输入并返回整数作为输出。由于Sums,Ranges,Trs等占用大量字节,因此仅实现多项式。



@alephalpha谢谢!
LegionMammal978 '18

可能不仅仅评估多项式就可以到达那里:#.(#^2-#)&@*Range实现了另一个常见的解决方案。(但是它也是17个字节。)我们可以在18个字节中实现朴素算法:Tr@#^2-#.#&@*Range
Misha Lavrov



3

05AB1E,8个字节

ÝDOnsnO-

说明:

ÝDOnsnO-     //Full program
Ý            //Push [0..a] where a is implicit input
 D           //Duplicate top of stack
  On         //Push sum, then square it
    s        //Swap top two elements of stack
     nO      //Square each element, then push sum
       -     //Difference (implicitly printed)

在线尝试!


LDnOsOn-我也是第一次尝试
魔术章鱼缸

3

C,C ++,46 40 37字节(#define),50 47 46字节(函数)

-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

并弄乱了运算符的优先级。功能版本没有这个问题


1
可以更换所有的解决了这个问题与字节的很多成本的宏n(n)。另外,F(n) n=> F(n)n不管。
扎卡里

可以重新排列return p*p/4-p*(n-~n)/6return(p/4-(n-~n)/6)*p
扎卡里

@Zacharý不,有时给我不好的结果,例如输入“ 3”为24而不是22,或者输入“ 24”为85200而不是85100。我怀疑是整数除法的原因
HatsuPointerKun

gh,永远不要忘记那件事。
扎卡里


2

Pyth,7个字节

sm**hdh

在这里在线尝试。

使用尼尔答案中的公式。

sm**hdhddQ   Implicit: Q=eval(input())
             Trailing ddQ inferred
 m       Q   Map [0-Q) as d, using:
    hd         Increment d
   *  hd       Multiply the above with another copy
  *     d      Multiply the above by d
s            Sum, implicit print 



2

05AB1E,6个字节

LnDƶαO

在线尝试!

说明

L         # push range [1 ... input]
 n        # square each
  D       # duplicate
   ƶ      # lift, multiply each by its 1-based index
    α     # element-wise absolute difference
     O    # sum

相同字节数的其他一些版本:

L<ān*O
Ln.āPO
L¦nā*O



2

MathGolf,6个字节

{î²ï*+

在线尝试!

计算 ķ=1个ñķ2ķ-1个

说明:

{       Loop (implicit) input times
 î²     1-index of loop squared
    *   Multiplied by
   ï    The 0-index of the loop
     +  And add to the running total

2

Clojure,58个字节

(fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s))))

在线尝试!


编辑:我误解了这个问题

Clojure中55,35个字节

#(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12)

在线尝试!


1
感谢您修复该问题。关于您的上一个条目,请注意,该(apply +字段比短(reduce +
Carcigenicate

@Carcigenicate谢谢!
TheGreatGeek

1
您可以编辑永久链接来运行其中一个测试用例吗?实际上,我不帮助不认识Clojure的人。
丹尼斯

2

cQuents17 15字节

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

1

APL(NARS),13个字符,26个字节

{+/⍵×⍵×⍵-1}∘⍳

使用公式Sum'w = 1..n'(w w(w-1))可能我写的与“ 1 +×⍳×⍳-1”相同;测试:

  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640


1

QBASIC,45 44字节

使用纯数学可以节省1个字节!

INPUT n
?n^2*(n+1)*(n+1)/4-n*(n+1)*(2*n+1)/6

在线尝试


上一个基于循环的答案

INPUT n
FOR q=1TO n
a=a+q^2
b=b+q
NEXT
?b^2-a

在线尝试!

注意,REPL进行了扩展,因为否则解释器将失败。


1

JAEL13 10字节

#&àĝ&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

1

05AB1E,6个字节

LDOšnÆ

在线尝试!

说明:

           # implicit input (example: 3)
L          # range ([1, 2, 3])
 DOš       # prepend the sum ([6, 1, 2, 3])
    n      # square each ([36, 1, 4, 9])
     Æ     # reduce by subtraction (22)
           # implicit output

Æ通常不会有用,但这是发光的时刻。这比天真LOnILnO-两个完整字节。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.