The sum of the squares of the first ten natural numbers is,
1
2![)]()
+ 2
2![)]()
+ ... + 10
2![)]()
= 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)
2![)]()
= 55
2![)]()
= 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.
Clojure: Running time = 1.76s
+-;pow
(defn pow [a b]
(loop [res 1 mult a shift b]
(if (= 0 shift)
res
(if (= 1 (rem shift 2))
(recur (* res mult) (* mult mult) (bit-shift-right shift 1))
(recur res (* mult mult) (bit-shift-right shift 1))
)
)
)
)
(defn p6 []
(println
(- (pow (apply + (range 1 101)) 2) (apply + (map #(pow % 2) (range 1 101))))
)
)
Erlang: Running time = 0.14s
+-%pow
pow(_,0)->1;
pow(1,_)->1;
pow(A,B)->pow(A,B,1).
pow(_,0,Res)->Res;
pow(Mult,B,Res) when B band 1 == 1 ->
pow(Mult*Mult,B bsr 1, Res*Mult);
pow(Mult,B,Res)->pow(Mult*Mult,B bsr 1, Res).
p6()->io:format("~w~n",[pow(lists:sum(lists:seq(1,100)),2)-lists:sum(lists:map(fun(X)->X*X end, lists:seq(1,100)))]).
Ruby: Running time = 0.02s
+-#Enumerable
module Enumerable
def sum
self.inject{|u,v|u+v}
end
def product
self.inject{|u,v|u*v}
end
def count(ob)
self.select{|i|i==ob}.length
end
def take_while
return [] unless yield(self.first)
if(self.class==Range)
evalPoint=self.first
evalPoint=evalPoint.succ while yield(evalPoint.succ) and not evalPoint==self.last
return self.first..evalPoint
else
s=self.to_a
upTo=1
upTo+=1 while yield(s[upTo]) and upTo<self.length
return self[0...upTo]
end
end
end
def p6
puts (1..100).sum**2-(1..100).map{|i|i**2}.sum
end
Scala: Running time = 0.18s
+-//pow
def pow(a: BigInt, b: Int)={
def loop(res: BigInt, mult: BigInt, shift:Int): BigInt={
if(shift==0) res
else{
if(shift%2==0) loop(res, mult*mult, shift >> 1)
else loop(res*mult, mult*mult, shift >>1)
}
}
loop(1,a,b)
}
def p6{
val r=(1 to 100)
println(pow(r.foldLeft(0)(_+_),2)-r.map(pow(_,2).intValue).foldLeft(0)(_+_))
}