Scala 10~1000质数求和

将 10~1000 的质数相加求和

object Work {
  def main(args: Array[String]): Unit = {
    println(sumPrimes(10, 1000))
  }

  def sumPrimes(from: Int,to: Int):Int = {
  	// val ints:Array[Int] = filter(from.to(to).toArray,x=>isPrime(x))
    val ints:Array[Int] = filter(from.to(to).toArray,isPrime)
    //这个地方不是调用isPrime,是把isPrime当成函数传递
    var sum = 0
    //println(ints.mkString(",")) 打印 ints 数组,元素与元素之间用逗号隔开
 	reduce(ints,_ + _)
  }
  //判断是否为质数
  def isPrime(n:Int) :Boolean = {
    for(i <- 2 until n if n % i ==0)
      return false
    return true
  }
  //过滤非质数,返回质数构成的集合
  def filter(arr:Array[Int],op:Int=>Boolean)={
    for(elem <- arr if op(elem))
      yield elem
  }
  //求数组之和
  def reduce (arr:Array[Int],op:(Int,Int)=>Int)={
    var lastReduce = arr(0)
    for(i <-1 until arr.length){
      lastReduce = op(lastReduce,arr(i))
    }
    lastReduce
  }
}

你可能感兴趣的:(Scala,题目)