Created
January 31, 2017 05:20
-
-
Save tekkoc/1a279db04735de906b14cba8728143c5 to your computer and use it in GitHub Desktop.
等差数列
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
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