Skip to content

Instantly share code, notes, and snippets.

@ponkotuy
Last active December 18, 2015 13:39
Show Gist options
  • Save ponkotuy/5791300 to your computer and use it in GitHub Desktop.
Save ponkotuy/5791300 to your computer and use it in GitHub Desktop.
Project Euler の問題44より。 http://projecteuler.net/problem=44 Scala版は遅くて使い物にならないのだが何故?
import std.stdio;
import std.math;
class Penta
{
private:
pure uint pentagonal(uint n) {
return n*(3*n - 1)/2;
}
pure uint[] pentagonals(uint n) {
uint[] result;
foreach(i; 0 .. (n + 1)) {
result ~= pentagonal(i);
}
return result;
}
pure bool isPenta(uint n) {
double dbl = (1.0 + sqrt(1.0 + 24*n))/6.0;
return pentas[cast(uint)dbl] == n ||
pentas[cast(uint)dbl + 1] == n;
}
public:
uint[] pentas;
this() {
pentas = pentagonals(20000);
}
bool exec(uint j, uint k) {
uint pj = pentas[j];
uint pk = pentas[k];
return isPenta(pj + pk) && isPenta(abs(pk - pj));
}
}
void main()
{
auto penta = new Penta;
for(int i=1; i!=10000; ++i) {
for(int j=i + 1; j!=10000; ++j) {
if(penta.exec(i, j)) {
uint diff = penta.pentas[j] - penta.pentas[i];
writeln(diff);
return;
}
}
}
}
unittest
{
assert(pentagonal(3) == 12);
assert(pentagonals(10) == [0, 1, 5, 12, 22, 35, 51, 70, 92, 117, 145]);
}
object Prob44_2 {
def pentagonal(n: Int) = n*(3*n - 1)/2
val pentagonals = Stream.from(0).map(pentagonal).takeWhile(_ < (Int.MaxValue >> 2)).toList
def isPenta(n: Int) = {
val dbl = (1.0 + math.sqrt(1 + 24*n))/6.0
val int = dbl.toInt
pentagonal(int) == n || pentagonal(int + 1) == n
}
def check(j: Int, k: Int): Boolean = {
val pj = pentagonals(j)
val pk = pentagonals(k)
isPenta(pj + pk) && isPenta((pj - pk).abs)
}
def main(args: Array[String]) {
val result = for {
i <- 1 to 10000
j <- (i + 1) to 10001
if check(i, j)
} yield (i, j)
println(result.head)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment