This is my first post!
I just got into programming a couple months ago. I created a program for finding weird numbers (see Weird number - Wikipedia).
It takes about 0.3 s for first 50 weird numbers.
If you have any questions about how it works or suggestions (such as if this is in the wrong place), let me know!
from itertools import combinations
from sympy import divisors
from time import time
start = time()
def main(): # Range of numbers [number1, number2]
min = 1
max = 26531 # below - Contains only weird numbers in range
even = [i for i in range(min + min % 2, max, 2) if (i % 3 != 0 and isweird(i) == 1)] # No multiple of 20 is weird
print("Even weird no:\n", even)
if max > 10**21: # No odd weird numbers below 10^21
if min < 10**21:
min = int(10**21 + 1)
odd = [i for i in range(min + min % 2 - 1, max, 2) if isweird(i) == i]
print("Odd weird no: ", odd)
def isweird(n): # Filters nonweird numbers
factors = divisors(n)
factors.remove(n) # Creates list of factors of n, excluding n
difference = sum(factors) - n
if difference <= 0: # If n is deficient or perfect, system exits
return
sum_factors = 0
factors.reverse()
for i in factors: # Checks for obvious nonweird
new = sum_factors + i # Stores new sum_factors in variable to save time
if new < n:
sum_factors = new
elif new == n:
return
included_factors = set(StopIteration if i <= difference else i for i in factors if i > difference) # Checks for factors that must be in combo that sums to n
factors = [i for i in factors if i not in included_factors]
newsum = n - sum(included_factors) # New sum
for i in range(len(factors) - (n % 2) * ((n - sum(included_factors) - len(factors)) % 2), 1, -(n % 2 + 1)): # Combos that sum to n
for j in combinations(factors, i):
if sum(j) == newsum:
return
return 1 # Weird n is passed back to main
main()
end = time()
print("Execution time: ", round(end - start, 2), "s")
Cyrus Polentschz
Below: nothing in particular - just wanted to share this program. It was moved to Python Help by a moderator.