Project Euler

Project Euler Problem 6

steloflute 2012. 5. 28. 00:45

Problem 6

14 December 2001

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

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

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.


Answer:
25164150

 

 

Solution in Perl

 

sub problem6 {
 my $sum = 0;
 my $sqSum = 0;
 for my $i ( 1 .. 100 ) {
  $sum += $i;
  $sqSum += $i * $i;
 }
 print $sum * $sum - $sqSum;
}

problem6();

 

# 2

for (1..100) {$s+=$_; $s2+=$_*$_;}
print $s*$s-$s2;

 

 

Python

 

def problem6():
    sumN = 0
    sqSum = 0
    for i in xrange(1, 101):
        sumN += i
        sqSum += i * i   
    print sumN * sumN - sqSum

 

 

Go

func problem6(){
    sumN := 0
    sqSum := 0
    for i :=1;i<=100;i++ {
        sumN += i
        sqSum += i * i   
    }
    fmt.Println(sumN * sumN - sqSum)
}

func main() {
 problem6()
}



C++


void problem6() {

    auto sumN = 0;

    auto sqSum = 0;

    for (auto i=1; i<=100; i++) {

        sumN += i;

        sqSum += i * i;

    }

    cout << sumN * sumN - sqSum;

}


 

Bash

 

function problem6 {
    local sum=0
    local sqSum=0
    for i in {1..100}; do
        ((sum += i))
        ((sqSum += i * i))
    done
    echo $((sum * sum - sqSum))
}

problem6



Javascript


var sumN=0, sqSum=0;
for(var i=1; i<=100; sumN+=i,sqSum+=i*i,i++);
sumN * sumN - sqSum


Racket

 

(define (problem6)
  (define sumN (apply + (range 1 101)))
  (define sqSum (apply + (map (lambda (x) (* x x)) (range 1 101))))
  (display (- (* sumN sumN) sqSum)))

(problem6)




; using sqr

#lang racket

(define (problem6)

  (define r (range 1 101))

  (define sumN (apply + r))

  (define sqSum (apply + (map sqr r)))

  (display (- (sqr sumN) sqSum)))

(problem6)

 

* Clojure

 

(defn problem6 []
  (def r (range 1 101))
  (defn sqr [x] (* x x))
  (println (- (sqr (apply + r)) (apply + (map sqr r)))))


* newLISP


(setq r (sequence 1 100))
(define (sqr x) (* x x))
(println (- (sqr (apply + r)) (apply + (map sqr r))))



'Project Euler' 카테고리의 다른 글

Project Euler Problem 8  (0) 2012.05.28
Project Euler Problem 7  (0) 2012.05.28
Project Euler Problem 5  (0) 2012.05.28
Project Euler Problem 4  (0) 2012.05.28
Project Euler Problem 211  (0) 2012.05.28