测试一个输入的Int是否是一个完美的数字 [英] Testing if an inputted Int is a perfect number

查看:160
本文介绍了测试一个输入的Int是否是一个完美的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 完美n =完美的数字,我在rosettacode上找到了一些有趣的代码: n == sum [i | i < -  [1..n-1],n`mod` i == 0] 

现在,我明白一个完美的数字是什么,我知道哪些数字被认为是完美的,但是我正在努力确定这些代码的哪些部分做什么。



据我了解,它正在处理输入数字的因素,并将它们组合在一起以查看它是否与输入本身匹配,但我不确定它是如何进行的这个。



如果有人可以用初学者友好的方式分解这段代码,我会非常感激。

解决方案

  n == sum [i | i<  -  [1..n-1],n'mod'i == 0] 
^^^^^^^^^
$ b $ i 从 1 n-1 (也就是说, [1,2,3,4 ... n-1]

  n == sum [i | i<  -  [1..n-1],n`mod` i == 0] 
^^^^^^

仅适用于 i 均匀分配 n 的值。丢弃不符合此要求的值。

  n == sum [i | i<  -  [1..n-1],n`mod` i == 0] 
^^^

在结果列表中包含 i

  n == sum [i | i<  -  [1..n-1],n`mod` i == 0] 
^^^^

将这个列表的元素添加到一起。

  n == sum [i | i<  -  [1..n-1],n`mod` i == 0] 
^^^^

返回 True iff总数等于 n


I've been looking into perfect numbers, and I found this interesting bit of code on rosettacode:

perfect n = n == sum [i | i <- [1..n-1], n `mod` i == 0]

Now, I understand what a perfect number is, and I know which numbers are considered perfect, however I'm struggling to work out which parts of this code do what.

I understand that it's working out the factors of the inputted number, and combining them together to see if it matches the input itself, but I'm not sure how it's doing this.

If anyone could possibly break down this bit of code in a beginner-friendly manner I'd be very appreciative.

解决方案

n == sum [i | i <- [1..n-1], n `mod` i == 0]
              ^^^^^^^^^

For i from 1 to n-1 (that is, [1, 2, 3, 4 ... n-1])

n == sum [i | i <- [1..n-1], n `mod` i == 0]
                              ^^^^^^

And only for those values where i evenly divides n. Discarding values that do not match this requirement.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
         ^^^

Include i in the result list.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
     ^^^^

Add the elements of this list together.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
^^^^

And return True iff the total equals n.

这篇关于测试一个输入的Int是否是一个完美的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆