You are given a list of integers. Write a function to find the "weird numbers". A weird number is an abundant number that is not a semi-perfect number. Please define abundant number, define semi-perfect number, write a function that solves this problem, and explain your algorithm.
Assistant
We are given: "You are given a list of integers. Write a function to find the 'weird numbers'. A weird number is an abundant number that is not a semi-perfect number. Please define abundant number, define semi-perfect number, write a function that solves this problem, and explain your algorithm."
So we need to output:
Define abundant number.
Define semi-perfect number.
Write a function that, given a list of integers, returns the weird numbers (i.e., those that are abundant but not semi-perfect).
Explain the algorithm.
We need to be careful: The definitions:
Abundant number: a number for which the sum of its proper divisors (excluding the number itself) is greater than the number. So if sum(proper divisors) > n, then n is abundant.
Semi-perfect number (also called pseudoperfect number): a number that is equal to the sum of some of its proper divisors. So there exists a subset of the proper divisors whose sum equals the number. A number that is abundant but not semi-perfect is called weird.
We need to write a function that takes a list of integers and returns the weird numbers from that list. We assume the list may contain arbitrary integers, possibly including negatives? But typically these definitions are for positive integers. So we should consider only positive integers? The problem says "list of integers", so we should filter out non-positive numbers? Since abundant and semi-perfect are defined for positive integers greater than 1? Actually 1: proper divisors of 1 are none, sum=0, so not abundant. So we can ignore numbers <=0. But to be safe, we can handle only positive integers and skip others.
Algorithm:
For each number n in the list (positive integer):
Compute proper divisors of n (all divisors except n itself).
Compute sum of proper divisors. If sum <= n, then n is not abundant, skip.
If abundant, then check if n is semi-perfect: determine if there exists a subset of the proper divisors that sums to n. This is a subset sum problem. Since proper divisors are distinct and we need to find a subset that sums exactly to n. We can use dynamic programming for subset sum. But note: the proper divisors can be many if n is large. But since we are given a list, we might have to handle numbers up to some size. We need an efficient algorithm. However, the subset sum problem is NP-complete in general, but the set of divisors is relatively small (number of divisors is O(sqrt(n))). For n up to, say, 10^5, number of divisors is at most a few hundred. So a DP with target sum n is feasible? But n could be large, and DP would require O(n * d) where d is number of divisors. That might be too heavy if n is very large (like 10^9). But we can use a different approach: since we only need to check if n is semi-perfect, we can use a bitset or a set of achievable sums. We can iterate through divisors and update a set of sums. That is O(d * max_sum) in worst case? Actually using a set we can do: start with {0}, for each divisor d, update set = set ∪ {s+d for s in set if s+d <= n}. But worst-case number of sums could be up to n, but we can cap at n. However, if n is large (like 10^6), that set might become large. But d is small, so the number of sums is at most min(2^d, n). Since d is O(sqrt(n)), 2^d could be huge if d is large? But d is not that large: for n=10^6, number of divisors is about 200? Actually maximum number of divisors for numbers up to 10^6 is around 240? So 2^240 is astronomical, but we don't generate all subsets, we merge sums, so the number of distinct sums is at most n+1. So worst-case we might have n+1 sums, which for n=10^6 is 1e6+1, that's acceptable. But if n is 10^9, then n+1 is 1e9+1, which is too many. But maybe the input list doesn't contain such huge numbers? We don't know. We need to design a reasonable algorithm. Possibly we can optimize by noticing that if n is abundant, then the sum of proper divisors > n, so the total sum S > n. For semi-perfect, we need a subset sum exactly n. There is a known fact: all multiples of a perfect number are semi-perfect? Not exactly. But we can try to use a DP with a boolean array of size n+1? That would be O(n) memory, which for large n is not feasible. Alternatively, we can use a bitset with bit operations, but still size O(n).
Maybe we can use a meet-in-the-middle approach? But d is small, so we can split divisors into two halves and compute all subset sums for each half (each half gives at most 2^(d/2) sums). Then we can check if there is a pair from the two sets that sums to n. That would be O(2^(d/2)) time and memory. Since d is at most around 1000? For n up to 10^9, number of divisors is at most about 1344 (for highly composite numbers). 2^(672) is impossible. So that doesn't work.
Actually, the maximum number of divisors for n up to 10^9 is 1344? That is for 735134400? That's around 1344 divisors. 2^(672) is astronomical. So meet-in-the-middle is not feasible.
But wait: for semi-perfect check, we don't necessarily need to consider all divisors? There is a known theorem: if n is abundant and not semi-perfect, it is weird. But to check semi-perfect, we can use a greedy algorithm? Not always correct. There is a known result: all abundant numbers that are multiples of a perfect number are semi-perfect? Actually, if n is abundant and not weird, it is semi-perfect. But we need an algorithm.
Maybe we can use a dynamic programming with a set that grows, but we can prune: we only care about sums up to n. And we can stop early if we find n. So we do:
def is_semi_perfect(n, divisors):
# divisors: list of proper divisors, sorted?
sums = set([0])
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
This uses a set to store all achievable sums < n. The size of sums can be up to n, but typically it's much less? But worst-case it could be n. However, for n large, this is problematic.
Alternatively, we can use a boolean array of size n+1 if n is not too large. But what is "too large"? We need to decide a threshold. Since the problem statement doesn't specify constraints, we might assume that the numbers in the list are moderate, say up to 10^5 or 10^6. But we can't be sure.
Maybe we can use an optimized algorithm: since the divisors come from the factorization, we can generate them efficiently. But the subset sum remains.
Another idea: There is a known fact that if n is abundant and the sum of its proper divisors is at least 2n, then it is semi-perfect? Not necessarily. Actually, a number is weird if it is abundant but not semi-perfect. Known weird numbers: 70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, 13790, 13930, 14770, 15212, 15654, 16030, 16310, 16730, 17050, 17470, 17570, ... They are relatively sparse. But we need a general method.
Given that the input is a list, we might have to handle each number individually. We can implement the subset sum with a set, and hope that the numbers are not astronomically large. Alternatively, we can use a bitset implemented as an integer if n is small enough? But Python integers can be arbitrarily large, but operations on large bitsets are slow.
Maybe we can optimize by sorting divisors in descending order? That might help find a solution faster if we use a recursive DFS with memoization? But worst-case still exponential.
Wait, there is a known algorithm for checking if a number is semi-perfect using the fact that the divisors come from the factorization? I recall that if n is abundant, then it is semi-perfect unless it is weird. But that doesn't help.
Given the typical constraints in programming problems, numbers might be up to 10^5 or 10^6. So we can use a DP array of booleans of size n+1. But if n is 10^6, that's 1e6 booleans, which is about 1MB, acceptable. If n is 10^7, that's 10MB, still maybe acceptable. But if n is 10^9, that's 1GB, not acceptable.
So we need a strategy: if n is large (say > 10^6), we might use the set method, but the set could also become large. However, note that the number of divisors d is O(sqrt(n)), so for n=10^9, d is about 1000. The number of distinct subset sums could be up to min(2^d, n). Since d=1000, 2^d is huge, but the actual number of distinct sums might be much less? Possibly not, it could be dense. But typical divisor sets are not random; they have structure. But worst-case we might still get many sums.
Maybe we can combine: use DP with a bitset using Python's int as bitset. For example, we can represent the set of achievable sums as a bitmask where bit i indicates sum i is achievable. We start with bit 0 set. Then for each divisor d, we do: mask |= mask << d. But we only care about bits up to n. However, if n is large, the mask would require n bits, so an integer of size n bits, which for n=10^9 is 125MB, still large but maybe manageable? But shifting such large integers is slow.
Alternatively, we can use a bytearray or list of booleans, but memory issues.
Given that this is an explanation for an interview-like question, we can assume the numbers are not extremely large, and we can use the DP with a set or a boolean list. We'll implement a function that first computes proper divisors efficiently (by iterating up to sqrt(n)). Then check abundance. Then for semi-perfect, we can use a dynamic programming with a set, and we break early if we find n. We can also sort divisors descending? That might help find n faster? Not necessarily.
We can also use an optimization: since the total sum of all proper divisors is S > n, we are looking for a subset sum exactly n. If we consider the complement: we want a subset with sum n, which is equivalent to a subset of the divisors that does not include some divisors summing to S-n. But that doesn't simplify.
Another idea: since S > n, we can also check if n is semi-perfect by checking if there is a subset of divisors that sums to n. We can use a BFS-like approach with a set of sums, but we limit to sums <= n. That is what we did.
We can also use recursion with memoization: dp(i, current_sum) where i is index in divisors list, but that's essentially the same.
Given the constraints unknown, I'll write a solution that uses the set method, and for very large n, it might be slow, but we can hope that in practice n is not huge. Alternatively, we can add a condition: if n > some threshold (say 10^5), we use the set method but with pruning: we can sort divisors in descending order and do DFS with iterative deepening? Not sure.
But for the purpose of this problem, we can present the straightforward approach and explain that for large numbers, we might need more advanced techniques.
Now, we need to write a function that takes a list and returns the weird numbers. So:
def find_weird_numbers(nums):
weird = []
for n in nums:
if n <= 0:
continue
divisors = proper_divisors(n)
total = sum(divisors)
if total <= n:
continue # not abundant
if is_semi_perfect(n, divisors):
continue # semi-perfect, not weird
weird.append(n)
return weird
We need to define proper_divisors(n): returns all divisors of n except n itself. We compute by iterating i from 1 to sqrt(n). For each i dividing n, add i and n//i if different and not n. Also exclude n itself.
But careful: proper divisors exclude n. So we don't include n.
Implementation:
def proper_divisors(n):
divs = set()
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divs.add(i)
if i != n//i:
divs.add(n//i)
divs.discard(n) # remove n if present (when n=1? but n>1 usually)
return sorted(divs) # sorted might help in subset sum? not necessary.
But for subset sum, order doesn't matter. But we might sort to possibly find solution faster? Not really.
Now is_semi_perfect(n, divisors): we need to check if there is a subset of divisors that sums to n.
We can implement:
def is_semi_perfect(n, divisors):
sums = set([0])
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
But this might be inefficient if sums grows large. We can try to use a list of booleans if n is small enough. How to decide? We can check if n is, say, less than 10^6, then use boolean list DP. Otherwise use set. But we don't know the scale. Alternatively, we can always use the set method, and hope that the number of sums doesn't explode. But worst-case it could be n.
Maybe we can combine: use a bitset if n is not too large. Let's set a threshold, say MAX_FOR_BITSET = 1000000. If n <= MAX_FOR_BITSET, we use a list of booleans of length n+1. That is efficient in time O(nd) but actually we iterate over d and for each we update the DP array? Actually the standard subset sum DP: dp[0]=True, for each divisor d, for s from n down to d: dp[s] = dp[s] or dp[s-d]. That is O(nd) time and O(n) space. That might be acceptable for n up to 10^6 and d up to a few hundred? That's about 10^6 * 200 = 200e6 operations, which is heavy but maybe in Python it's borderline. But we can optimize by using bitset operations: mask = 1 (bit0 set), then for each d: mask |= mask << d, and then check if the nth bit is set. But we need to limit the mask to n bits to avoid huge integers. We can do: mask = (mask | (mask << d)) & ((1 << (n+1)) - 1). That is efficient in Python if n is up to a few thousand? But for n=10^6, shifting a 1e6-bit integer is expensive? Actually Python integers are arbitrary precision, but bit operations on large integers are implemented in C and might be reasonably fast? Possibly but I'm not sure. For n=10^6, that's 125KB, so shifting is okay. But for n=10^7, 1.25MB, still okay. For n=10^8, 12.5MB, might be slower but still manageable? But we need to be cautious.
Given that this is a conceptual answer, we can present a simple implementation using the set method, and mention that for larger numbers we might need a more efficient approach.
But let's think: The known weird numbers are relatively small (the first few are below 10000). So perhaps in practice we only deal with numbers up to, say, 10^5. So the set method might be acceptable.
However, the set method's worst-case size could be up to n, so if n=10^5, that's 100k elements in the set, and for each divisor we iterate over the set. That could be O(d * |sums|). In worst-case, |sums| could grow linearly with n, so total O(d*n). That is similar to the DP array method but with overhead of set operations. So it might be slower.
Maybe we can use the boolean list DP only when n is not too large, and for larger n use the set method but with early termination? But the set method might also become large.
Alternatively, we can use a recursive DFS with memoization using the state (index, current_sum). That would be O(d * n) in worst-case as well, but with recursion overhead.
Given the constraints are unspecified, I'll implement the boolean list DP for n up to a threshold (say 10^5) and for larger n use the set method but with a check: if the number of divisors is small enough, we can use the set method safely. But if n is huge and d is large, both methods might be heavy. But perhaps in such cases the number is not weird because abundant numbers with many divisors are often semi-perfect? Not necessarily.
Wait, there is a known fact: all abundant numbers with a certain property are semi-perfect. But I'm not sure.
Given that this is an explanation, we can present a straightforward algorithm and mention that for very large numbers, more optimized techniques (like using meet-in-the-middle for large divisor sets) might be required, but for typical inputs the provided method works.
I think for the purpose of this answer, we can implement the set method and hope it's okay.
But let's test on known weird number 70: proper divisors of 70: 1,2,5,7,10,14,35. Sum = 74 >70, abundant. Is it semi-perfect? Check if any subset sums to 70: 35+14+10+7+5? 35+14=49, +10=59, +7=66, +5=71 too high; 35+14+10+1=60; 35+14+7+5+1? 35+14=49, +7=56, +5=61, +1=62; 35+10+7+5+1? 35+10=45, +7=52, +5=57, +1=58; 35+14+10+7? 66; 35+14+10+5? 64; 35+14+7+5? 61; 35+10+7+5? 57; 35+14+10+7+2? 68; 35+14+10+5+2? 66; 35+14+7+5+2? 63; 35+10+7+5+2? 59; 35+14+10+7+5+2? 73; 35+14+10+7+5+1? 72; etc. Actually 70 is known to be weird, so should return True for abundant and False for semi-perfect. Our set method: start with {0}, add 1 -> {0,1}; add 2 -> {0,1,2,3}; add 5 -> {0,1,2,3,5,6,7,8}; add 7 -> {0,1,2,3,5,6,7,8,7+? actually careful: we iterate and update. Let's simulate quickly: after 1: {0,1}; after 2: from 0:2, from 1:3 -> {0,1,2,3}; after 5: from 0:5,1:6,2:7,3:8 -> {0,1,2,3,5,6,7,8}; after 7: from each: 0+7=7 (already),1+7=8 (already),2+7=9,3+7=10,5+7=12,6+7=13,7+7=14,8+7=15 -> new:9,10,12,13,14,15 -> set now includes 0..8,9,10,12,13,14,15; after 10: from each existing sum s: s+10. We'll get many. Eventually we might get 70? But we know 70 is not semi-perfect, so we shouldn't get 70. But wait, is 70 semi-perfect? Actually 70 is weird, so it is not semi-perfect. But let's check: sum of all proper divisors is 74, so we need a subset sum to 70. That means we need to leave out divisors summing to 4. The divisors are {1,2,5,7,10,14,35}. Is there a subset that sums to 4? Only 1+2+? 1+2=3, not 4; 1+? no. So we cannot get 70 by including all? Actually if we take all divisors, sum=74, so to get 70 we need to exclude divisors that sum to 4. But we cannot exclude a combination that sums to 4 because the smallest divisors are 1 and 2, sum=3, and 4 is not achievable. So no subset sums to 70. So our algorithm should return False for is_semi_perfect(70, divisors). But wait, maybe there is a subset that sums to 70 without using all? Actually we want a subset that sums exactly to 70, not necessarily all. So we need to check all subsets. The set method will eventually have 70 if possible. But we must be careful: we are only adding sums less than n, but we check for equality when adding. So it should work.
But note: if the total sum of all divisors is S, and we are looking for a subset that sums to n, we can also consider that if we find a subset that sums to n, we are done. But we might also consider that we can use the complement: if we find a subset that sums to S-n, then the complement sums to n. But that doesn't change the complexity.
So the set method is correct.
Now, we need to define abundant and semi-perfect in the explanation.
Algorithm explanation:
For each number in the list:
a. Compute its proper divisors.
b. Compute sum of proper divisors. If sum <= number, skip (not abundant).
c. If abundant, check if the number is semi-perfect by solving the subset sum problem on the set of proper divisors with target equal to the number.
d. If not semi-perfect, then it is weird; add to result.
Return the list of weird numbers.
For efficiency, we can optimize divisor computation by iterating up to sqrt(n). For subset sum, we use a set to keep track of all achievable sums less than n, updating iteratively. If at any point we achieve n, we return True.
We should also note that the empty subset sum is 0.
Complexity:
Divisor computation: O(sqrt(n)).
Subset sum: In worst-case, the set of sums can grow up to n, and we iterate over d divisors, so O(d * n) in worst-case. But d is O(sqrt(n)), so worst-case O(n^(3/2)). That is expensive for large n. But for typical n (say up to 10^5), it's acceptable? n^(3/2) for n=10^5 is about 10^7.5? Actually (10^5)^(3/2)=10^(7.5)=3e7, which is borderline in Python but maybe okay. For n=10^4, it's 10^6. So if numbers are moderate, it's fine.
We can mention that for very large numbers, we might need a more efficient algorithm, but for the scope of this problem we assume numbers are reasonable.
Alternatively, we can use dynamic programming with a boolean array of size n+1, which also has O(n*d) time and O(n) space. But we can choose the set method to avoid allocating large arrays for large n? Actually the set method could also use a lot of memory if many sums are generated.
Maybe we can use a hybrid: if n is small (say <= 10000), use boolean array; otherwise use set. But we don't know.
Given that this is a text answer, we can present a clean implementation using the set method and explain its complexity.
Now, write the code in Python.
We'll define:
def proper_divisors(n):
if n <= 1:
return []
divs = set()
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divs.add(i)
if i != n // i:
divs.add(n // i)
divs.discard(n)
return sorted(divs)
def is_semi_perfect(n, divisors):
sums = {0}
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
def find_weird_numbers(nums):
result = []
for n in nums:
if n <= 0:
continue
divs = proper_divisors(n)
total = sum(divs)
if total <= n:
continue
if not is_semi_perfect(n, divs):
result.append(n)
return result
But careful: is_semi_perfect might be slow if we don't sort divisors? Sorting might help? Possibly if we process larger divisors first, we might reach n faster? Not necessarily. But we can try to sort in descending order? Actually if we process large divisors first, the set of sums might grow more quickly? Not sure. But we can leave as sorted ascending from proper_divisors? Actually proper_divisors returns sorted ascending. That's fine.
But note: the set method may generate many sums. We can also prune: if the current sum s plus the remaining total (sum of remaining divisors) is less than n, we can break? But we are not doing recursion, we are iterating. Actually we can keep track of the sum of remaining divisors? Not easily.
Alternatively, we can use a BFS-like approach but with a queue? Same.
Maybe we can improve by using a bitset if n is not too large. Let's implement a version that uses a boolean list for n up to some limit, and for larger n uses the set method. But we need to decide a limit. Since the problem statement doesn't specify, we can choose a limit like 10^5. But then if n is larger than that, we use set. But if n is huge, set might also be huge. But maybe for huge n, the number of divisors is large and the set might become huge too. But perhaps we can also use an early exit: if the sum of all divisors is exactly n? That would be perfect, but we already know it's abundant so sum > n. But we can also check if any single divisor equals n? That's impossible because divisors are proper, so d < n. So no.
Another optimization: if n is even and all divisors are even? Not sure.
Given that this is an explanation, we can present the simple version and note that for large inputs, more efficient algorithms exist.
I think it's acceptable.
Now, we need to output the definitions and the algorithm explanation.
So final answer should include:
Definitions:
Abundant number: a positive integer n such that the sum of its proper divisors (all divisors except n itself) is greater than n.
Semi-perfect number: a positive integer n for which there exists a subset of its proper divisors that sums exactly to n.
Then the function: find_weird_numbers(nums) returns a list of numbers from nums that are abundant but not semi-perfect.
Algorithm:
For each number n in the input list:
If n <= 0, skip.
Compute all proper divisors of n.
Calculate the sum of these divisors. If the sum <= n, then n is not abundant; skip.
If abundant, check if n is semi-perfect by solving the subset sum problem: determine if there is a subset of the proper divisors that sums to n. This is done using dynamic programming with a set of achievable sums.
If no such subset exists, n is weird; add to result.
Return the result.
Complexity: For each n, divisor computation is O(sqrt(n)). The subset sum check in worst-case can be O(d * n) where d is number of divisors (O(sqrt(n))), so overall per number O(n^(3/2)) in worst-case. But in practice, the set of achievable sums is often much smaller than n, and for typical inputs the algorithm runs efficiently.
We can also mention that we could use a boolean array for DP when n is small to improve speed.
Now, write the code accordingly.
But note: the set method might be memory heavy for large n. So maybe we should use the boolean array method when n is not too large. Let's implement a threshold, say 100000. If n <= 100000, we use a list dp of size n+1, else we use the set method.
But then for n=100000, dp array has 100001 booleans, that's about 100KB, fine. The time for dp is O(n*d). For n=100000 and d~300, that's 30e6 operations, which in Python might be a few seconds? Possibly acceptable for a single number? But if the list has many numbers, it could be slow. But we don't know.
Maybe we can always use the set method because it might be faster in practice due to fewer operations? Actually the set method iterates over the current set for each divisor, so the total number of operations is roughly the total number of new sums generated. That could be less than n*d.
I'll stick to the set method for simplicity.
But wait, there is a bug: In the set method, we are updating sums with new_sums while iterating over sums. That's fine because we don't want to use the newly added sums in the same iteration? Actually the standard subset sum DP processes each item and updates the set of achievable sums by adding the item to all previously achievable sums. But if we do:
sums = {0}
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n: return True
if ns < n: new_sums.add(ns)
sums.update(new_sums)
This ensures that we only use each divisor once. But note: we are iterating over sums which is the set before adding new_sums. That is correct. However, we might miss some combinations? Actually it's correct: at step i, sums contains all achievable sums using the first i divisors. Then for the next divisor, we add d to each of those to get new sums, and then merge. So it's fine.
But we can also do: sums = sums | {s+d for s in sums if s+d <= n} but that would use the updated sums during iteration? In Python, set comprehension creates a new set, so it's safe. But we are doing two-step: new_sums then update.
Alternatively, we can do: new_sums = set()
for s in sums:
ns = s + d
if ns == n: return True
if ns < n: new_sums.add(ns)
sums |= new_sums
That's what we have.
Now, what about duplicates? Divisors are distinct, so no issue.
One more optimization: we can sort divisors in descending order? That might cause the set to grow more slowly? Actually if we add large divisors first, then the sums become large quickly, and we might hit n early. But it could also prune some sums because if s+d > n, we skip. But if we start with large divisors, many s+d will exceed n and we skip, so the set might grow slower? Possibly. But we might also find n earlier if a large divisor plus some combination gives n. So it might be beneficial to sort divisors in descending order. But it's not guaranteed. We can try both. But for consistency, we can sort in descending order to potentially find a solution faster. However, the set method's performance depends on order. In worst-case, it might still generate many sums. But we can try.
I'll sort divisors in descending order before passing to is_semi_perfect? Actually in proper_divisors we return sorted ascending. We can change to descending? Or we can sort in is_semi_perfect. Let's sort descending in is_semi_perfect to potentially improve early termination.
But careful: if we sort descending, the set of sums might become dense earlier? Not sure. But we can do:
def is_semi_perfect(n, divisors):
divisors = sorted(divisors, reverse=True)
sums = {0}
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
But note: if we sort descending, we might miss combinations that use smaller numbers? No, because we consider all sums from previous steps. The order doesn't affect the final set of achievable sums, but it might affect when we find n. So sorting descending might help find n earlier if a large divisor is part of the solution. But if the solution uses only small divisors, we might still find it later. So it's a heuristic.
We can also break early if we find n.
Now, also we should consider that the sum of all divisors is S > n. So if we are processing divisors and the current sum s plus the sum of all remaining divisors is less than n, then we cannot reach n. But we don't have the sum of remaining easily. But we could precompute the suffix sums if we sort in some order. That could prune: for each divisor, we know the total sum of divisors from current to end. But we are updating sums set, so it's not straightforward.
Maybe we can do a recursive DFS with branch and bound? That might be more efficient in practice because we can prune when current sum exceeds n or when current sum + remaining total < n. But worst-case still exponential.
Given that d is small, we could do a DFS with memoization (state = index, current_sum). That would be O(d * n) states worst-case, but we can prune if current_sum > n. But still the number of states could be large.
But perhaps the set method is simpler and works for moderate n.
I'll go with the set method with descending sort.
Now, what about the case when n is 12? 12 is abundant? Proper divisors: 1,2,3,4,6. Sum=16>12, so abundant. Is it semi-perfect? Yes: 6+4+2=12. So not weird. So should not be included.
Test: proper_divisors(12) -> [1,2,3,4,6]. Sorted descending: [6,4,3,2,1]. is_semi_perfect: start sums={0}. d=6: new_sums from 0:6 -> {6}. sums={0,6}. d=4: from 0:4, from 6:10 -> new_sums={4,10}. sums={0,4,6,10}. d=3: from each: 0+3=3,4+3=7,6+3=9,10+3=13 -> new_sums={3,7,9}. sums now includes 3,7,9. d=2: from each: 0+2=2,4+2=6,6+2=8,10+2=12 -> we get 12! So returns True. Good.
For 70: divisors descending: [35,14,10,7,5,2,1]. Let's simulate quickly: sums={0}. d=35: new_sums={35}. sums={0,35}. d=14: from 0:14, from 35:49 -> new_sums={14,49}. sums={0,14,35,49}. d=10: from 0:10,14:24,35:45,49:59 -> new_sums={10,24,45,59}. sums now includes those. d=7: from each: 0+7=7,14+7=21,35+7=42,49+7=56,10+7=17,24+7=31,45+7=52,59+7=66 -> new_sums={7,21,42,56,17,31,52,66}. d=5: from all: we get many: 0+5=5,14+5=19,35+5=40,49+5=54,10+5=15,24+5=29,45+5=50,59+5=64,7+5=12,21+5=26,42+5=47,56+5=61,17+5=22,31+5=36,52+5=57,66+5=71 -> we get 5,19,40,54,15,29,50,64,12,26,47,61,22,36,57,71. Note 70 not yet. d=2: from all: we add 2 to each existing sum. Existing sums are many: 0,5,7,10,12,14,15,17,19,21,22,24,26,29,31,35,36,40,42,45,47,49,50,52,54,56,57,59,61,64,66,71,... plus others. Adding 2: we get 2,7,9,12,14,16,19,21,23,24,26,28,31,33,37,39,41,44,46,48,49,51,52,54,56,58,59,61,63,66,68,73,... Note 70 not there? Actually from 68? 68+2=70 if 68 is present. Do we have 68? From previous step, we had 66? 66+2=68, not 70. From 64+2=66, already. From 61+2=63. From 59+2=61. From 57+2=59. From 56+2=58. From 54+2=56. From 52+2=54. From 50+2=52. From 49+2=51. From 47+2=49. From 45+2=47. From 42+2=44. From 40+2=42. From 36+2=38. From 35+2=37. From 31+2=33. From 29+2=31. From 26+2=28. From 24+2=26. From 22+2=24. From 21+2=23. From 19+2=21. From 17+2=19. From 15+2=17. From 12+2=14. From 10+2=12. From 7+2=9. From 5+2=7. From 0+2=2. So we get many even numbers, but 70? Check if any sum before adding 2 was 68? We had 66, 64, 61, etc. Did we have 68? From earlier: after d=5, we had sums like 66? Yes from 59+5=64? Wait, after d=5 we had: from 59+5=64, from 66? We had 66 from d=7? Actually after d=7 we had 66 (from 59+7). So after d=5, we have 66? But we add 5 to each sum from after d=7. The sums after d=7 included 66. Then when processing d=5, we add 5 to 66 to get 71 (we got that). But we also have 66 itself? It remains because we don't remove old sums. So after d=5, sums includes 66. Then when processing d=2, we add 2 to 66 to get 68. So we have 68. Then when processing d=1, we add 1 to 68 to get 69, and to other numbers. But we never get 70? Actually from 69+1=70? But 69 is from 68+1? But we process d=1 last. After d=2, sums includes 68. Then d=1: from 68+1=69, not 70. But also from 69? We don't have 69 yet. So we need 69 to get 70. But do we have 69? From 68+1=69. But then we would need to add 1 again? No, we only add each divisor once. So we cannot use 1 twice. So we need a subset that sums to 70. The subset that sums to 70 would be all divisors except 4? But 4 is not a divisor. Actually to get 70, we need sum of some divisors =70. The total sum is 74, so we need to exclude divisors summing to 4. But we cannot exclude a subset that sums to 4 because the only way to get 4 is 1+? 1+3? but 3 is a divisor? Actually 3 is a divisor? Wait, 70's divisors: 1,2,5,7,10,14,35. There is no 3 or 4. So we cannot exclude a subset summing to 4. So no subset sums to 70. So our algorithm should return False. But in the above simulation, after processing all divisors, we never got 70. So it returns False. Good.
But wait, did we miss a combination like 35+14+10+7+5? That's 35+14=49, +10=59, +7=66, +5=71 >70. 35+14+10+7+2=68, +1=69. 35+14+10+5+2+1? 35+14=49, +10=59, +5=64, +2=66, +1=67. 35+14+7+5+2+1? 35+14=49, +7=56, +5=61, +2=63, +1=64. 35+10+7+5+2+1? 35+10=45, +7=52, +5=57, +2=59, +1=60. 14+10+7+5+2+1? 14+10=24, +7=31, +5=36, +2=38, +1=39. So no 70. So correct.
Now, what about a number that is abundant and semi-perfect? Like 12 we tested. What about 18? Proper divisors:1,2,3,6,9. Sum=21>18. Subset: 9+6+3=18. So semi-perfect. Our algorithm should find 18.
So the code seems correct.
But we must be careful: in is_semi_perfect, we are only considering sums less than n when adding to new_sums. But what if we have a sum exactly n? We return immediately. That's fine.
But what if we have a sum s that is less than n, but s+d > n? We skip. So we never store sums > n. That's correct because we only care about sums up to n.
Now, one more optimization: we can break early if the maximum possible sum from remaining divisors plus current max sum is less than n? Not needed.
Now, we need to present the code in the answer.
We also need to explain the algorithm.
So final answer structure:
Definitions:
Abundant number: ...
Semi-perfect number: ...
Function: find_weird_numbers(nums)
Steps as above.
Algorithm explanation:
For each number, compute proper divisors by iterating up to sqrt(n).
Check abundance.
For semi-perfect check, use dynamic programming with a set to store all achievable sums less than n. Iterate through each divisor, and for each existing sum, add the divisor to create new sums. If any new sum equals n, the number is semi-perfect.
If not semi-perfect, add to result.
Complexity analysis.
Code.
We might also include test cases or example.
But the problem says "write a function that solves this problem", so we need to provide the function.
Now, I'll write the code in a clean way.
One more thing: We should handle the case when n is 1? Proper divisors of 1 are none, sum=0, not abundant. So skip.
Also, negative numbers: skip.
Now, code:
def proper_divisors(n):
"""Return a sorted list of proper divisors of n (excluding n itself)."""
if n <= 1:
return []
divs = set()
i = 1
while i * i <= n:
if n % i == 0:
divs.add(i)
if i != n // i:
divs.add(n // i)
i += 1
divs.discard(n)
return sorted(divs)
def is_semi_perfect(n, divisors):
"""Check if n is semi-perfect given its proper divisors."""
# Sort divisors in descending order to potentially reach n faster.
divisors = sorted(divisors, reverse=True)
sums = {0}
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
def find_weird_numbers(nums):
"""
Given a list of integers, return a list of the weird numbers.
A weird number is an abundant number that is not semi-perfect.
"""
weird = []
for n in nums:
if n <= 0:
continue
divs = proper_divisors(n)
total = sum(divs)
if total <= n:
continue # not abundant
if not is_semi_perfect(n, divs):
weird.append(n)
return weird
That's it.
But we can add a small optimization: in is_semi_perfect, if the sum of all divisors is less than n, then it's impossible to reach n? But we already know total > n because abundant. But the sum of all divisors is total, which is > n. So we cannot use that to prune early.
We can also check if any single divisor equals n? But proper divisors are less than n, so no.
So that's the code.
Now, we should also consider that the set method might become slow if n is large. But we can mention in explanation that for large n, a different approach might be needed.
Maybe we can incorporate a threshold: if n > 100000, use the set method but with a limit on the size of sums? Not really.
Alternatively, we can use the boolean array DP for n up to, say, 100000, and for larger n use the set method. But then for n between 100000 and, say, 1e9, set method might still be heavy if n is huge. But maybe such large n rarely appear? We don't know.
Given that this is a conceptual answer, I think it's fine.
Now, let's produce the final answer.
We need to output definitions, function, and explanation.
I'll structure the answer as:
Definitions:
Abundant number: ...
Semi-perfect number: ...
Algorithm:
For each number n in the input list:
a. Skip if n <= 0.
b. Compute all proper divisors of n.
c. Compute the sum of these divisors. If sum <= n, n is not abundant; skip.
d. If abundant, check if n is semi-perfect using subset sum.
e. If not semi-perfect, n is weird; add to result.
Return result.
Subset Sum Check:
We use dynamic programming with a set to store all achievable sums using a subset of the divisors. Initialize with sum 0. For each divisor d, we create new sums by adding d to each existing sum. If any new sum equals n, return True. After processing all divisors, if n not reached, return False.
Complexity:
Proper divisor computation: O(sqrt(n)).
Subset sum: In worst-case O(d * n) time and O(n) space, where d is number of divisors (O(sqrt(n))). So per number worst-case O(n^(3/2)). But in practice, the set of achievable sums is often much smaller than n, and for typical inputs (n up to 10^5) it runs quickly.
Code:
[Python code as above]
We might also include an example: find_weird_numbers([70, 12, 18, 20]) returns [70] because 70 is abundant but not semi-perfect, while 12,18,20 are semi-perfect? Actually 20: proper divisors:1,2,4,5,10 sum=22>20. Is 20 semi-perfect? 10+5+4+1=20? 10+5+4+1=20, yes. So not weird.
So example: [70, 12, 18, 20, 836] (836 is weird) returns [70,836].
Now, I'll write the final answer.
Definitions
Abundant number: A positive integer ( n ) is called abundant if the sum of its proper divisors (all positive divisors excluding ( n ) itself) is greater than ( n ).
Formally, let ( \sigma(n) ) be the sum of all positive divisors of ( n ). Then ( n ) is abundant if ( \sigma(n) - n > n ), i.e., ( \sigma(n) > 2n ). Equivalently, if ( s(n) = \sum_{d|n, d<n} d > n ).
Semi-perfect number (also known as pseudoperfect number): A positive integer ( n ) is semi-perfect if there exists a subset of its proper divisors whose sum equals exactly ( n ).
That is, there is some ( S \subseteq { d : d|n, d<n } ) such that ( \sum_{d \in S} d = n ).
A weird number is an abundant number that is not semi-perfect.
Algorithm
For each integer ( n ) in the input list:
Skip non-positive numbers – abundant and semi-perfect are defined for positive integers only.
Compute proper divisors of ( n ).
This is done efficiently by iterating ( i ) from ( 1 ) to ( \sqrt{n} ). For each ( i ) that divides ( n ), add both ( i ) and ( n/i ) (if distinct) to a set, then remove ( n ) itself.
Check abundance: compute the sum ( s ) of the proper divisors. If ( s \le n ), ( n ) is not abundant → skip.
Check semi-perfection using a subset-sum approach:
We need to know whether some subset of the proper divisors sums exactly to ( n ).
Use dynamic programming with a set sums that stores all achievable sums using a subset of the divisors processed so far (initially {0}).
Process each divisor ( d ) (optionally sorted in descending order to possibly find a solution earlier). For each existing sum ( s ) in sums, compute ( ns = s + d ).
If ( ns = n ), ( n ) is semi-perfect → stop and return True.
If ( ns < n ), add ( ns ) to a temporary set of new sums.
After iterating over all ( s ) for the current ( d ), merge the new sums into sums.
If the loop finishes without reaching ( n ), ( n ) is not semi-perfect.
If ( n ) is abundant and not semi-perfect, it is weird → add to the result list.
Return the collected weird numbers.
Complexity Analysis
Proper divisor computation: ( O(\sqrt{n}) ) per number.
Semi-perfect check:
Let ( d ) be the number of proper divisors (worst-case ( O(\sqrt{n}) )). The dynamic programming set may contain up to ( n ) distinct sums in the worst case. Each divisor iterates over the current set, leading to ( O(d \cdot |sums|) ) operations. In the worst case ( |sums| = O(n) ), so the time is ( O(d \cdot n) = O(n^{3/2}) ). Space is ( O(|sums|) = O(n) ).
In practice, the set of achievable sums is often much smaller than ( n ), and for typical inputs (e.g., ( n \le 10^5 )) the algorithm runs quickly.
Reference Implementation (Python)
python
def proper_divisors(n):
"""Return a sorted list of proper divisors of n (excluding n itself)."""
if n <= 1:
return []
divs = set()
i = 1
while i * i <= n:
if n % i == 0:
divs.add(i)
if i != n // i:
divs.add(n // i)
i += 1
divs.discard(n) # ensure n is not included
return sorted(divs) # ascending order
def is_semi_perfect(n, divisors):
"""Check whether n is semi-perfect given its proper divisors."""
# Sorting in descending order may help reach n faster in many cases.
divisors = sorted(divisors, reverse=True)
sums = {0} # achievable sums
for d in divisors:
new_sums = set()
for s in sums:
ns = s + d
if ns == n:
return True
if ns < n:
new_sums.add(ns)
sums.update(new_sums)
return False
def find_weird_numbers(nums):
"""
Given a list of integers, return a list of the weird numbers.
A weird number is an abundant number that is not semi-perfect.
"""
weird = []
for n in nums:
if n <= 0:
continue
divs = proper_divisors(n)
total = sum(divs)
if total <= n:
continue # not abundant
if not is_semi_perfect(n, divs):
weird.append(n)
return weird