Create a gist now

Instantly share code, notes, and snippets.

S-99 P31-P35 blank
// *** S-99: Ninety-Nine Scala Problems ***
// http://aperiodic.net/phil/scala/s-99/
//
// wget http://www.scala-tools.org/repo-releases/org/scalatest/scalatest_2.9.1/1.6.1/scalatest_2.9.1-1.6.1.jar
// scala -cp scalatest*.jar s99-31-35.scala
import org.scalatest.matchers.ShouldMatchers._
class NotImplementedYet extends RuntimeException
// P31: Determine whether a given integer number is prime.
object P31 {
case class P31Int(i: Int) {
def isPrime: Boolean = {
throw new NotImplementedYet
}
}
implicit def fromIntToP31Int(i: Int): P31Int = P31Int(i)
def test {
{
1.isPrime should equal(false)
2.isPrime should equal(true)
3.isPrime should equal(true)
4.isPrime should equal(false)
5.isPrime should equal(true)
6.isPrime should equal(false)
7.isPrime should equal(true)
8.isPrime should equal(false)
9.isPrime should equal(false)
10.isPrime should equal(false)
11.isPrime should equal(true)
12.isPrime should equal(false)
13.isPrime should equal(true)
14.isPrime should equal(false)
15.isPrime should equal(false)
}
}
}
// P32: Determine the greatest common divisor of two positive integer numbers.
// Use Euclid's algorithm.
object P32 {
def gcd(m: Int, n: Int): Int = {
throw new NotImplementedYet
}
def test {
{
gcd(36, 63) should equal(9)
gcd(42, 21) should equal(21)
gcd(13, 17) should equal(1)
}
}
}
// P33: Determine whether two positive integer numbers are coprime.
// Two numbers are coprime if their greatest common divisor equals 1.
object P33 {
case class P33Int(i: Int) {
def isCoprimeTo(j: Int): Boolean = {
throw new NotImplementedYet
}
}
implicit def fromIntToP33Int(i: Int): P33Int = P33Int(i)
def test {
{
35.isCoprimeTo(64) should equal(true)
9.isCoprimeTo(8) should equal(true)
5.isCoprimeTo(5) should equal(false)
12.isCoprimeTo(18) should equal(false)
9.isCoprimeTo(33) should equal(false)
}
}
}
// P34: Calculate Euler's totient function phi(m).
// Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r <= m) that are coprime to m.
object P34 {
case class P34Int(i: Int) {
import P33._
def totient: Int = {
throw new NotImplementedYet
}
}
implicit def fromIntToP34Int(i: Int): P34Int = P34Int(i)
def test {
{
10.totient should equal(4) // 1,3,7,9
11.totient should equal(10) // 1,2,3,4,5,6,7,8,9,10
}
}
}
// P35: Determine the prime factors of a given positive integer.
// Construct a flat list containing the prime factors in ascending order.
object P35 {
case class P35Int(i: Int) {
def primeFactors: List[Int] = {
throw new NotImplementedYet
}
}
implicit def fromIntToP35Int(i: Int): P35Int = P35Int(i)
def test {
{
315.primeFactors should equal(List(3,3,5,7))
120.primeFactors should equal(List(2,2,2,3,5))
30030.primeFactors should equal(List(2,3,5,7,11,13))
}
}
}
P31.test
P32.test
P33.test
P34.test
P35.test
// vim: set ts=4 sw=4 et:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment