请编写程序,由系统随机产生一个正整数 n(1<n<50000),根据菜单提示,选择输出小 于 n 的以下 7 种特殊数据中的一种:(1)完全数,(2)亲密数,(3)水仙花数,(4)阶乘和 数,(5)自守数,(6)孪生素数;直到用户退出系统。
时间: 2024-05-14 07:15:39 浏览: 88
ChitGPT: 好的,这个问题可以通过python代码来解决。以下是一个简单的程序,可以生成小于给定整数n的七种特殊数中的任意一种,并且可以帮助您退出系统。
```
import math
def isPerfect(n):
sum = 1
i = 2
while i * i <= n:
if n % i == 0:
sum += i + n / i
i += 1
if sum == n and n != 1:
return True
else:
return False
def isAmicable(a, b):
if (sumFactors(a) == b and sumFactors(b) == a):
return True
else:
return False
def sumFactors(n):
sum = 0
for i in range(1, n):
if (n % i == 0):
sum += i
return sum
def isNarcissistic(n):
digits = []
temp = n
while (temp > 0):
digits.append(temp % 10)
temp = temp // 10
numDigits = len(digits)
sum = 0
for i in range(0, numDigits):
sum += math.pow(digits[i], numDigits)
if (sum == n):
return True
else:
return False
def isFactorialSum(n):
i = 1
sum = 1
while(sum < n):
i += 1
sum *= i
return True if sum == n else False
def isSelfAdjoint(n):
strNum = str(n)
digitCount = len(strNum)
for i in range(1, digitCount + 1):
if int(strNum[-i:]) == n:
return True
return False
def isTwinPrime(n):
if isPrime(n) and isPrime(n - 2):
return True
elif isPrime(n) and isPrime(n + 2):
return True
else:
return False
def isPrime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
menu = "请输入您想输出的特殊数:\n1.完全数\n2.亲密数\n3.水仙花数\n4.阶乘和数\n5.自守数\n6.孪生素数\n7.退出程序\n"
while True:
n = int(input("请输入一个整数n(1<n<50000): "))
choice = int(input(menu))
while choice != 7:
if choice == 1:
perfectNumbers = []
for i in range(1, n):
if (isPerfect(i)):
perfectNumbers.append(i)
print("小于n的完全数有:", perfectNumbers)
elif choice == 2:
amicableNumbers = []
for i in range(1, n):
for j in range(i + 1, n):
if isAmicable(i, j):
amicableNumbers.append([i,j])
print("小于n的亲密数有:", amicableNumbers)
elif choice == 3:
narcissisticNumbers = []
for i in range(1, n):
if isNarcissistic(i):
narcissisticNumbers.append(i)
print("小于n的水仙花数有:", narcissisticNumbers)
elif choice == 4:
factorialSumNumbers = []
for i in range(1, n):
if isFactorialSum(i):
factorialSumNumbers.append(i)
print("小于n的阶乘和数有:", factorialSumNumbers)
elif choice == 5:
selfAdjointNumbers = []
for i in range(1, n):
if isSelfAdjoint(i):
selfAdjointNumbers.append(i)
print("小于n的自守数有:", selfAdjointNumbers)
elif choice == 6:
twinPrimeNumbers = []
for i in range(1, n):
if isTwinPrime(i):
twinPrimeNumbers.append(i)
print("小于n的孪生素数有:", twinPrimeNumbers)
else:
print("输入有误,请重新输入")
choice = int(input(menu))
print("程序已退出")
```
请问您对代码有什么疑问吗?
阅读全文