fork(3) download
  1. /**
  2.  * Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
  3.  * 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
  4.  * shows the first 11 ugly numbers. By convention, 1 is included.
  5.  * Write a program to find and print the 150th ugly number.
  6.  *
  7.  */
  8. object Main extends App {
  9. var uglyNumbers = List(1)
  10. val n = 20
  11.  
  12. var i2 = 0;
  13. var i3 = 0;
  14. var i5 = 0;
  15.  
  16. // initialize three choices for the next ugly numbers
  17. var next_multiple_2 = uglyNumbers(i2) * 2;
  18. var next_multiple_3 = uglyNumbers(i3) * 3;
  19. var next_multiple_5 = uglyNumbers(i5) * 5;
  20.  
  21. for (i <- 0 to n) {
  22. val nextUglyNumber = min(next_multiple_2, next_multiple_3, next_multiple_5)
  23. uglyNumbers = uglyNumbers :+ nextUglyNumber
  24.  
  25. if (nextUglyNumber == next_multiple_2) {
  26. i2 = i2 + 1
  27. next_multiple_2 = uglyNumbers(i2) * 2
  28. }
  29.  
  30. if (nextUglyNumber == next_multiple_3) {
  31. i3 = i3 + 1
  32. next_multiple_3 = uglyNumbers(i3) * 3
  33. }
  34.  
  35. if (nextUglyNumber == next_multiple_5) {
  36. i5 = i5 + 1
  37. next_multiple_5 = uglyNumbers(i5) * 5
  38. }
  39. }
  40.  
  41. for (uglyNumber <- uglyNumbers)
  42. print(uglyNumber + " ")
  43.  
  44. def min(a: Int, b: Int, c: Int): Int = (a, b, c) match {
  45. case _ if (a <= b && a <= c) => a
  46. case _ if (b <= a && b <= c) => b
  47. case _ => c
  48. }
  49. }
Success #stdin #stdout 0.38s 382016KB
stdin
Standard input is empty
stdout
1   2   3   4   5   6   8   9   10   12   15   16   18   20   24   25   27   30   32   36   40   45