합계 제곱 차


15

처음 10 개의 자연수의 제곱의 합은 12+22++102=385

처음 10 개의 자연수의 합의 제곱은

(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
이의 하위 집합입니다 질문
coinheringaahing 케어 드

1
시퀀스를 0 인덱스 할 수 있습니까? 즉 자연수는 n?
조 왕


3
@ Enigma 정말 많은 답변이 여기에 대한 답변으로 쉽게 포팅되지 않기 때문에 이것이 대상의 복제본이라고 생각하지 않으므로 뭔가 추가됩니다.
Jonathan Allan

답변:


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.
버블 러

7

TI 기본 (TI-83 시리즈), 12 11 바이트

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

구현 (n22)(12+13n). 에서의 입력을 받아Ans, 예를 들어, 실행10:prgmX입력에 대한 결과를 계산합니다10.


의 좋은 사용 nCr!
Lynn


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 -x, 9 8 5 4 bytes

õ²í*

Try it


Explanation

õ        :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 bytes

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

(Much longer) Port of Jonathan Allan's Jelly answer.

Try it online!


Go tacit and combine the drops: +/¯1↓⍳×1⌽⍳×⍳
Adám

3

APL (Dyalog), 16 bytes

((×⍨+/)-(+/×⍨))⍳

Try it online!

 (×⍨+/)            The square  self) of the sum (+ fold)
       -           minus
        (+/×⍨)     the sum of the square
(             )⍳   of [1, 2,  input].

(+/×⍨)1⊥×⍨ as per tip.
Adám

1
A further byte could be saved by keeping the inside (×⍨1⊥⍳)-⍳+.×⍳
Kritixi Lithos

3

Mathematica, 21 17 bytes

-4 bytes thanks to alephalpha.

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

Pure function. Takes an integer as input and returns an integer as output. Just implements the polynomial, since Sums, Ranges, Trs, etc. take up a lot of bytes.



@alephalpha Thanks!
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 :

Sum of numbers between 1 and n = n*(n+1)/2
Sum of squares between 1 and n = n*(n+1)*(2n+1)/6

So the formula to get the answer is simply (n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6

And now to "optimize" the byte count, we break parenthesis and move stuff around, while testing it always gives the same result

(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

Notice the pattern p = n*n+1 = n*n+n, so in the function, we declare another variable int p = n*n+n and it gives :

p*p/4 - p*(2n+1)/6

For p*(p/4-(2*n+1)/6) and so n*(n+1)*(n*(n+1)/4 - (2n+1)/6), it works half the time only, and I suspect integer division to be the cause ( f(3) giving 24 instead of 22, f(24) giving 85200 instead of 85100, so we can't factorize the macro's formula that way, even if mathematically it is the same.

Both the macro and function version are here because of macro substitution :

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.