@Scala
两个题目
定义函数判断一个整数是否为质数
def isPrime(n:Int):Boolean={
for(i <- 2 until math.ceil(math.sqrt(n)).toInt){
if(n%i==0) return false
}
true
}
def isPrime1(n:Int):Boolean={
for(i <- 2 until n if n%i==0){
return false
}
true
}
println(isPrime1(9))
println(isPrime(17))
定义函数计算100-10000所有的质数的和
一般方法
def sumPrime(from:Int,to:Int):Int={
var sum:Int=0
for(n <- from to to if isPrime(n)) sum+=n
sum
}
使用filter reduce
filter帮助我们过滤出质数,然后把这些质数交给reduce进行求和
def sumPrimes(from:Int,to:Int):Int={
//filter帮助我们过滤出质数,然后把这些质数交给reduce进行求和
val ints:Array[Int]=filter(from to to toArray,isPrime)
reduce(ints, (x, y) => x + y)
}
def reduce(arr:Array[Int],op:(Int,Int)=>Int):Int={
var lastreduce:Int=arr(0)
for(i<-1 until(arr.length)){
lastreduce= op(lastreduce,arr(i))
}
lastreduce
}
def filter(arr:Array[Int],op:Int=>Boolean)={
for(ele<-arr if op(ele)) yield ele
}
运行结果
def main(args: Array[String]): Unit = {
println(isPrime1(9))
println(isPrime(17))
println(sumPrime(10, 13))
println(sumPrimes(10, 11))
println(sumPrimes(10, 15))
}