+ 3
Solve the perfect number challenge in Python using recursion?
Here is my code - it works, but I think there must be a more elegant, i. e. recursive way to solve this. Any suggestions? https://code.sololearn.com/c5mTkOy5AtSa/?ref=app
7 Answers
+ 3
Not saying this is efficient but here is a simple recursion
f=lambda n,i=1,s=0:s*(i==n) or f(n,i+1,s+i*(not n%i))
print(f(n)==n)
+ 4
Not recursion yet, but I made your code more efficient.
https://code.sololearn.com/c23JCCEnQGeK/?ref=app
Can you check it for me please?
+ 4
Great code everyone. I think recursion in this case, would be inelegant.
+ 3
No recursion. Used list comprehension. Line 2 gets all the factors of the number and puts them in a list and line 3 checks if the sum of those elements equal the number and prints if it perfect or not ... The second code is in case I wanted to define an outside function
https://code.sololearn.com/c0F3jkXQyrfh/?ref=app
https://code.sololearn.com/cnin5373R4bb/?ref=app
+ 2
https://www.jstor.org/stable/2042285?seq=1#page_scan_tab_contents
+ 2
Or use Euler's formula
https://code.sololearn.com/cf91DP6E3ERY/?ref=app
+ 1
thanks Johannes. look at Eulers method too