Can';找不到错误(Euler#8项目(Scala))
所以我一直在用Scala做Euler项目的问题,但似乎被困在了8号上,它要求在1000位数字中找到13个相邻的数字,这些数字的乘积最大。我写的代码如下Can';找不到错误(Euler#8项目(Scala)),scala,Scala,所以我一直在用Scala做Euler项目的问题,但似乎被困在了8号上,它要求在1000位数字中找到13个相邻的数字,这些数字的乘积最大。我写的代码如下 import scala.io.Source val digits1000File = "1000Digit.txt" val lines = Source.fromFile(digits1000File).getLines.toList val digits1000 = lines.mkString("") //finds the grea
import scala.io.Source
val digits1000File = "1000Digit.txt"
val lines = Source.fromFile(digits1000File).getLines.toList
val digits1000 = lines.mkString("")
//finds the greatest product of n adjacent digits in the string
def greatestAdjProduct(digits : String,n: Int): Int = {
val xs = for(
i <- 0 until digits.length - n
) yield digits.substring(i,i+n)
xs.map(s =>s.map(_.asDigit).product).max
}
println(s"euler 8 = ${greatestAdjProduct(digits1000,13)}")
导入scala.io.Source
val digits1000File=“1000Digit.txt”
val lines=Source.fromFile(digits1000File).getLines.toList
val digits1000=行.mkString(“”)
//查找字符串中n个相邻数字的最大乘积
def greatestAdjProduct(数字:字符串,n:Int):Int={
val xs=用于(
i.s.map(u.asDigit).product).max
}
println(s“euler 8=${GreateStatdjProduct(digits1000,13)}”)
这对4位数字正确,但对13位数字似乎不起作用。谁能帮我一下吗?您的代码有多个问题
首先,在理解
时,应该使用to
,而不是until
,以避免一次过一个bug。您还可以将上述理解替换为val xs=digits.slideing(n)
其次,您有一个溢出错误。13位的乘积可能太大,无法装入Int
。由于整数溢出,以下返回值为-754810903:
"9999999999999".map(_.asDigit).product
要解决此问题,可以使用BigInt
:
"9999999999999".map(d => BigInt(d.asDigit)).product
Long
在这里也适用,但是BigInt
是一个更通用的解决方案。您的代码有多个问题
首先,在理解时,应该使用to
,而不是until
,以避免一次过一个bug。您还可以将上述理解替换为val xs=digits.slideing(n)
其次,您有一个溢出错误。13位的乘积可能太大,无法装入Int
。由于整数溢出,以下返回值为-754810903:
"9999999999999".map(_.asDigit).product
要解决此问题,可以使用BigInt
:
"9999999999999".map(d => BigInt(d.asDigit)).product
Long
在这里也适用,但是BigInt
是一个更通用的解决方案。首先,在理解时,您应该使用to
而不是直到以避免一个错误导致一个错误。您还应该尝试将代码简化为a以帮助解决问题。首先,在理解时,您应该使用to
,而不是,直到,以避免一个错误一个错误地关闭。您还应该尝试将代码简化为一个新的版本,以帮助解决问题。