HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Solving Project Euler problem #48 in Scala

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
problemsolvingscalaprojecteuler

Problem

I'm trying to learn some Scala and decided to try to tackle some Project Euler problems.

For problem #48, coming from a Python background, my solution is the following one-liner:

print ( (1 to 1000).map(i => BigInt(i).pow(i)).sum % BigInt(10).pow(10) )


Is this idiomatic? Is there a simpler/more readable solution?

Solution

Your solution is clean but doesn't scale well. A well known optimization for a^k mod m is to perform all computations modulus m. If m is sufficiently small, we furthermore can switch to native types (this is not the case here !).

val n = 1000
val m = BigInt(10).pow(10)
(for (i <- 1 to n) yield BigInt(i).modPow(i,m)).sum % m


Rounded avarage timing results (Scala 2.9.1 with -optimize) :

n                     1000     | 10000
Initial solution       4.8 ms  |  6700 ms
Fold left              4.8 ms  |  6700 ms
My humble version      0.5 ms  |     5 ms

Code Snippets

val n = 1000
val m = BigInt(10).pow(10)
(for (i <- 1 to n) yield BigInt(i).modPow(i,m)).sum % m
n                     1000     | 10000
Initial solution       4.8 ms  |  6700 ms
Fold left              4.8 ms  |  6700 ms
My humble version      0.5 ms  |     5 ms

Context

StackExchange Code Review Q#15974, answer score: 3

Revisions (0)

No revisions yet.