object Euler03 {
type Factor = Long
type Number = Long
type Factors = List[Factor]
/* Returns the largest prime factor of the given
* number.It first computes all the prime factors of the given
* number and then returns the largest among them.
*/
def largestPrimeFactor (x: Number): Factor =
primeFactors(x).max
/* Returns the prime factors of the given number x. For instance
* if the number x equals to 5, it returns List(2,3).
*/
def primeFactors(x: Number): Factors = {
val numUpToSqrt = (2L to math.sqrt(x).toLong)
val divisibleBy = numUpToSqrt.find(x % _ == 0)
divisibleBy match {
case None => List(x)
// x is a prime number and not divisible by any
case Some(d) => d :: primeFactors(x/d)
}
}
}
This blog-post is about UVa 136: Ugly Number, a trivial, but interesting UVa problem. The crux involves computing 1500th Ugly number, where a Ugly number is defined as a number whose prime factors are only 2, 3 or 5. Following illustrates a sequence of Ugly numbers:
1,2,3,4,5,6,8,9,10,12,15...
Using F#, we can derive 1500th Ugly Number in F#’s REPL as follows.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In this context, the primary function the determines whether a number is a Ugly number or not–isUglyNumber–is outlined as follows. As we can see, it is a naive algorithm that can be further optimized using memoization (as listed here).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
After computing the 1500th Ugly number in this manner, we submit the Java source code listed below. For complete source code. please visit this gist. Alternatively, this script is also available at tryfsharp.org for further introspection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The underlying concepts of UVa 371: Ackermann Functions have been discussed in great details in our post of Collatz problem. In this post, we simply outlines an ad-hoc algorithm as a solution to this problem as follows.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters