平方和の差


15

最初の10個の自然数の平方和は、 12+22++102=385

最初の10個の自然数の合計の2乗は、

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

したがって、最初の10個の自然数の二乗和と和の二乗の差は

3025385=2640

指定された入力nについて、最初のn個の自然数の二乗和と和の二乗との差を求めます。

テストケース

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

この課題は、プロジェクトオイラー#6で初めて発表されました。

受賞基準

  • 入力が負またはゼロの場合の動作についてのルールはありません。

  • 最短の答えが勝ちです。


4
この課題には、勝利基準(例:コードゴルフ)が必要です
-dylnan

2
これは、この質問のサブセットです
共謀している

1
シーケンスに0のインデックスを付けることはできますか?すなわち、自然数はn
ジョーキング


3
@Enigmaここでの多くの答えはその答えになるように簡単に移植できないので、これがターゲットの複製だとは本当に思いません。
ジョナサンアラン

回答:




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⊥⍳×⍳×1-⍨⍳)10
バブラー

7

TI-Basic(TI-83シリーズ)、12 11バイト

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

実装(n22)(12+13n)。入力を受け取ります。Ansたとえば、実行10:prgmXしてinputの結果を計算します10


の素敵な使用nCr
リン


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






3

Mathematica、21 17バイト

alephalphaのおかげで-4バイト。

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

純粋な機能。入力として整数を受け取り、出力として整数を返します。Sums、Ranges、Trsなどが多くのバイトを占めるため、多項式を実装するだけです。



@alephalphaありがとう!
-LegionMammal978

It's possible to get there without just evaluating the polynomial: #.(#^2-#)&@*Range implements another common solution. (But it's also 17 bytes.) And we can implement the naive algorithm in 18 bytes: Tr@#^2-#.#&@*Range.
Misha Lavrov



3

05AB1E, 8 bytes

ÝDOnsnO-

Explanation:

Ý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)

Try it online!


LDnOsOn- was my first attempt too.
Magic Octopus Urn

3

C, C++, 46 40 37 bytes ( #define ), 50 47 46 bytes ( function )

-1 byte thanks to Zacharý

-11 bytes thanks to ceilingcat

Macro version :

#define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6

Function version :

int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;}

Thoses lines are based on thoses 2 formulas :

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) gives 3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22
F(5-2) gives 5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30

and mess up with the operator precedence. the function version does not have this problem


1
You could fix up the problem with the macros at the cost of A LOT of bytes by replacing all the n with (n). Also, F(n) n=>F(n)n regardless.
Zacharý

It's possible to rearrange return p*p/4-p*(n-~n)/6 to return(p/4-(n-~n)/6)*p.
Zacharý

@Zacharý No, it gives me bad results sometimes like 24 instead of 22 for input "3", or 85200 instead of 85100 for input "24". I suspect integer division to be the cause of that
HatsuPointerKun

Ugh, always forget about that.
Zacharý


2

Pyth, 7 bytes

sm**hdh

Try it online here.

Uses the formula in Neil's answer.

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 bytes

LnDƶαO

Try it online!

Explanation

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

Some other versions at the same byte count:

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



2

MathGolf, 6 bytes

{î²ï*+

Try it online!

Calculates k=1n(k2(k1))

Explanation:

{       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 bytes

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

Try it online!


Edit: I misunderstood the question

Clojure, 55, 35 bytes

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

Try it online!


1
Thanks for fixing that. And just a heads up regarding your last entry, (apply + is shorter than (reduce +.
Carcigenicate

@Carcigenicate Thanks!
TheGreatGeek

1
Could you edit your permalink to run one of the test cases? As it is, I doesn't help people who don't know Clojure.
Dennis

2

cQuents, 17 15 bytes

b$)^2-c$
;$
;$$

Try it online!

Explanation

 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 chars, 26 bytes

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

use the formula Sum'w=1..n'(ww(w-1)) possible i wrote the same some other wrote + or - as "1⊥⍳×⍳×⍳-1"; test:

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


1

QBASIC, 45 44 bytes

Going pure-math saves 1 byte!

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

Try THAT online!


Previous, loop-based answer

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

Try it online!

Note that the REPL is a bit more expanded because the interpreter fails otherwise.


1

JAEL, 13 10 bytes

#&àĝ&oȦ

Try it online!

Explanation (generated automatically):

./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 bytes

LDOšnÆ

Try it online!

Explanation:

           # 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

Æ isn't useful often, but this is its time to shine. This beats the naïve LOnILnO- by two whole bytes.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.