计算长整型数据类型范围内的值

问题描述 投票:0回答:1

我正在学习 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]

scala
1个回答
0
投票

看起来 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
  }
© www.soinside.com 2019 - 2024. All rights reserved.