Skip to content

Instantly share code, notes, and snippets.

@tekkoc
Created January 31, 2017 05:20
Show Gist options
  • Save tekkoc/1a279db04735de906b14cba8728143c5 to your computer and use it in GitHub Desktop.
Save tekkoc/1a279db04735de906b14cba8728143c5 to your computer and use it in GitHub Desktop.
等差数列
object Main {
def arithmeticSequence(n: Int, d: Int = 1): List[Int] = {
require(n > 0)
@scala.annotation.tailrec
def f(i: Int, acc: List[Int]): List[Int] = i match {
case 0 => acc
case _ => f(i - 1, i * d :: acc)
}
f(n, Nil)
}
def main(args: Array[String]) {
// List(1, 2, 3, 4, 5)
println(arithmeticSequence(5))
// 15
println(arithmeticSequence(5).sum)
// List(3, 6, 9, 12)
println(arithmeticSequence(4, 3))
// 30
println(arithmeticSequence(4, 3).sum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment