Clojure 检查数字是整数还是非整数有理数
我如何测试一个数字,看看它是整数还是非整数有理数 扰流板警告取自4clojure.com问题 上下文 考虑这一功能:Clojure 检查数字是整数还是非整数有理数,clojure,Clojure,我如何测试一个数字,看看它是整数还是非整数有理数 扰流板警告取自4clojure.com问题 上下文 考虑这一功能: (defn qux [n i] (reduce + (range 1 (/ n i)))) 范围中的最后一个元素是小于n且可被i整除的正整数数 user> (qux 10 3) ; 3, 6, & 9 are divisible by 3, sum(1, 2, 3) = 6 6 user> (qux 10 5) ; 5 is divisible by 5
(defn qux [n i]
(reduce + (range 1 (/ n i))))
范围中的最后一个元素是小于n且可被i整除的正整数数
user> (qux 10 3) ; 3, 6, & 9 are divisible by 3, sum(1, 2, 3) = 6
6
user> (qux 10 5) ; 5 is divisible by 5, sum(1) = 1
1
我想生成总和,而不生成范围。sum1..N=NN+1/2用于救援。
问题是N是严格小于N/i的最大整数。我的错误尝试是:
(defn how-many [n i]
(int (/ n i)))
(defn sum-1-to-N [n]
(/ (* n (+ n 1)) 2))
(defn qux-prime [n i]
(sum-1-to-N (how-many n i)))
user> (qux-prime 10 5)
3
因此,我想测试/n I的结果,如果它是整数,则减去1,否则使用int进行截断。不使用floor是因为我不想导入整个数字塔,因为我不知道如何在4clojure上执行此操作。您可以使用:
下面是一个完整的示例:
defn qux素数[ni]
让[r/n i]
n如果是整数?r dec r int r]
/*n+n 1 2
您可以使用:
下面是一个完整的示例:
defn qux素数[ni]
让[r/n i]
n如果是整数?r dec r int r]
/*n+n 1 2
我在另一个环境中遇到了这种情况,并发现
(if (== (int n) n) ; test to see if n is an integer - done this way (instead
(do-if-true) ; of integer?) so that float integers will be detected
(do-if-false)) ; correctly
效果很好
分享和享受。我在另一个环境中遇到这种情况,并发现
(if (== (int n) n) ; test to see if n is an integer - done this way (instead
(do-if-true) ; of integer?) so that float integers will be detected
(do-if-false)) ; correctly
效果很好
共享和享受。有几个核心函数可以直接处理整数,由于您的问题涉及这些,因此可能比使用int函数强制要好一些: 这给了qux: 我用以下材料将其固定: 在我的mbp上:
========= 364347 9361
...
Execution time mean : 6.111392 ms [=> with reduce]
...
Execution time mean : 69.042004 µs [=> with quot, rem]
...
Execution time mean : 294.989561 µs [=> with int, integer?]
...
在处理特定于整数的函数时,您的性能似乎得到了显著提高。有几个核心函数可以直接处理整数,由于您的问题是处理这些函数,因此可能比使用int函数强制要好一些: 这给了qux: 我用以下材料将其固定: 在我的mbp上:
========= 364347 9361
...
Execution time mean : 6.111392 ms [=> with reduce]
...
Execution time mean : 69.042004 µs [=> with quot, rem]
...
Execution time mean : 294.989561 µs [=> with int, integer?]
...
看起来,在处理特定于整数的函数时,您会获得显著的性能提升。对于浮点整数,您不需要==int n吗?因为int和float不是=?@ShannonSeverance-这就是我从内存输入而不是复制得到的结果。很好。对于浮点整数,不需要==int n吗?因为int和float不是=?@ShannonSeverance-这就是我从内存输入而不是复制得到的结果。很好,很好,处理了不同的类,这些类包含不同大小的整数。我看得不够远,在检查int?之后停了下来。很好,处理不同的类,它们包含不同大小的整数。我看得不够远,在检查int?后停了下来?。
========= 364347 9361
...
Execution time mean : 6.111392 ms [=> with reduce]
...
Execution time mean : 69.042004 µs [=> with quot, rem]
...
Execution time mean : 294.989561 µs [=> with int, integer?]
...