我正在学习 scala,并认为这会很简单且直接,但是每次尝试都会导致
More than Int.MaxValue elements.
错误。我正在尝试使用 Long
类型来计算某个范围内的所有奇怪事件。
看起来好像;
count
、size
和length
都处理类型Int
。那么我可以使用哪些方法来获取正确的值?:
def oddCount(n: Long): Long = {
(1L to n by 2L).size // Though this would reduce the size of the range
// Range.Long(1L, n, 1L).count(_ % 2 != 0) Another way I tried
}
>>> More than Int.MaxValue elements.
例如:
输入 n=7 应该输出 3,因为从 1 到 7 有 3 个奇数 => [1, 3, 5]
看起来 cats 有一个
count
返回 Long
但我不会为此添加第三方库。def oddCount(n: Long): Long =
LazyList.range(start = 1L, end = n).foldLeft(OL) { case (acc, x) =>
if ((x % 2) != 0) acc + 1L else acc
}