defmain(args: Array[String]): Unit = { //传统方法完成 1-50 的求和任务 val now: Date = newDate() val dateFormat: SimpleDateFormat = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss") val date = dateFormat.format(now)
println("date=" + date) //输出时间 var res = BigInt(0) var num = BigInt(1) var maxVal = BigInt(99999999l) //BigInt(99999999l)[测试效率大数] while (num <= maxVal) { res += num num += 1 } //耗时18s println("res=" + res) //res=4999999950000000 //再一次输出时间 val now2: Date = newDate() val date2 = dateFormat.format(now2) println("date2=" + date2) //输出时间 } }
defmain(args: Array[String]): Unit = { // 递归的方式来解决 //传统方法完成 1-50 的求和任务 val now: Date = newDate() val dateFormat: SimpleDateFormat = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss") val date = dateFormat.format(now) println("date=" + date) //输出时间
defmx(num: BigInt, sum: BigInt): BigInt = { if (num <= 99999999l) return mx(num + 1, sum + num) elsereturn sum }
//测试 var num = BigInt(1) var sum = BigInt(0) var res = mx(num,sum) //耗费16s println("res=" + res) //输出:res=4999999950000000
//再一次输出时间 val now2: Date = newDate() val date2 = dateFormat.format(now2) println("date2=" + date2) //输出时间 } }
3. 应用案例:最大值
求最大值
1 2 3 4 5 6 7 8
//大话java数据结构 defmax(xs: List[Int]): Int = { if (xs.isEmpty) thrownew java.util.NoSuchElementException if (xs.size == 1) xs.head elseif (xs.head > max(xs.tail)) xs.head else max(xs.tail) }