Created
June 20, 2013 19:39
-
-
Save cimi/5825917 to your computer and use it in GitHub Desktop.
Scala coding dojo 20/06/2013 - Code Kata - Prime Factors Calculator
http://craftsmanship.sv.cmu.edu/exercises/prime-factors-kata
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
import java.util | |
import scala.collection.mutable.ListBuffer | |
object PrimeFactorCalculator { | |
def prime(number: Integer):Boolean = { | |
if (number < 2) return false | |
if (number == 2) return true | |
for (i <- 3 to Math.sqrt(number.toDouble).toInt by 2 if (number % i == 0)) | |
return false | |
true | |
} | |
def primeFactors(number: Integer):List[Int] = { | |
val factors:ListBuffer[Int] = new ListBuffer[Int]() | |
for (i <- 2 to number) | |
if (number % i == 0 && prime(i)) { | |
factors += i | |
} | |
println(factors) | |
factors.toList | |
} | |
} |
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
import org.scalatest.FunSpec | |
class PrimeFactorCalculatorTest extends FunSpec { | |
describe("Prime factor PrimeFactorCalculator") { | |
it("should identify prime numbers") { | |
assert(!PrimeFactorCalculator.prime(0)) | |
assert(PrimeFactorCalculator.prime(3)) | |
assert(!PrimeFactorCalculator.prime(35)) | |
assert(PrimeFactorCalculator.prime(2)) | |
assert(PrimeFactorCalculator.prime(17)) | |
assert(!PrimeFactorCalculator.prime(1)) | |
assert(!PrimeFactorCalculator.prime(-11)) | |
} | |
it("should output a list of prime factors for a number") { | |
assert(PrimeFactorCalculator.primeFactors(15) == List(3, 5)) | |
assert(PrimeFactorCalculator.primeFactors(17) == List(17)) | |
assert(PrimeFactorCalculator.primeFactors(0) == List()) | |
assert(PrimeFactorCalculator.primeFactors(1) == List()) | |
assert(PrimeFactorCalculator.primeFactors(-1) == List()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment