HighProduct.scala 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. object HighProduct {
  2. def main(arg: Array[String]) {
  3. var max = List(BigInt(0), BigInt(0),
  4. BigInt(0));
  5. val digits = List(0, 1, 2, 3, 4, 5, 6,
  6. 7, 8, 9);
  7. for (c <- digits.combinations(4)) {
  8. // Sort the digits so that the
  9. // highest number gets built
  10. val a = c.sorted(Ordering[Int]);
  11. val b = (digits filterNot a.contains).
  12. sorted(Ordering[Int]);
  13. // calculate number a
  14. var anum = BigInt(0);
  15. for ((digit, place) <- a.zipWithIndex) {
  16. anum += digit *
  17. scala.math.pow(10, place).
  18. toInt;
  19. }
  20. // calculate number b
  21. var bnum = BigInt(0);
  22. for ((digit, place) <- b.zipWithIndex) {
  23. bnum += digit *
  24. scala.math.pow(10, place).
  25. toInt;
  26. }
  27. // calculate number a
  28. if (anum * bnum > max(0)) {
  29. max = List(anum * bnum, anum, bnum);
  30. }
  31. }
  32. println("%d • %d = %d".format(max(1),
  33. max(2),
  34. max(0)));
  35. }
  36. }