Skip to content

Python Program to Check Krishnamurthy Number #2248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions maths/krishnamurthy_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
== Krishnamurthy Number ==
It is also known as Peterson Number
A Krishnamurthy Number is a number whose sum of the
factorial of the digits equals to the original
number itself.

For example: 145 = 1! + 4! + 5!
So, 145 is a Krishnamurthy Number
"""


def factorial(digit: int) -> int:
"""
function to calculate factorial of each digit
"""

return 1 if (digit == 0 or digit == 1) else (digit * factorial(digit - 1))


def krishnamurthy(number: int) -> bool:
"""
>>> krishnamurthy(145)
True

>>> krishnamurthy(240)
False

>>> krishnamurthy(1)
True
"""

factSum = 0
duplicate = number
while duplicate > 0:
factSum += factorial(duplicate % 10)
duplicate //= 10
return factSum == number


if __name__ == "__main__":
print("Program to check whether a number is a Krisnamurthy Number or not")
number = int(input("Enter number: ").strip())
print(
f"{number} is {'' if krishnamurthy(number) else 'not '} a Krishnamurthy Number."
)
34 changes: 34 additions & 0 deletions maths/perfect_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
== Perfect Number ==
In number theory, a perfect number is a positive integer that is equal to the sum of
its positive divisors, excluding the number itself.
For example: 6 ==> divisors[1, 2, 3, 6]
Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6
So, 6 is a Perfect Number

Other examples of Perfect Numbers: 28, 486, ...

https://en.wikipedia.org/wiki/Perfect_number
"""


def perfect(number: int) -> bool:
"""
>>> perfect(27)
False
>>> perfect(28)
True
>>> perfect(29)
False

Start from 1 because dividing by 0 will raise ZeroDivisionError.
A number at most can be divisible by the half of the number except the number
itself. For example, 6 is at most can be divisible by 3 except by 6 itself.
"""
return sum(i for i in range(1, ((number // 2) + 1)) if number % i == 0) == number


if __name__ == "__main__":
print("Program to check whether a number is a Perfect number or not.......")
number = int(input("Enter number: ").strip())
print(f"{number} is {'' if perfect(number) else 'not '} a Perfect Number.")