We are given a list of integers. We need to find the "lucky numbers" in that list. A lucky number is defined as a number that is prime and also the sum of its digits is prime.
Steps:
- We need a helper function to check if a number is prime.
- We need a helper function to compute the sum of digits of a number.
- Then for each number in the list, we check:
a. If the number itself is prime.
b. If the sum of its digits is prime.
- If both conditions are true, then it's a lucky number.
However, note that the problem says "list of integers", so we might get negative numbers? But prime numbers are defined for natural numbers greater than 1. So we should only consider positive integers greater than 1. Also, note that 1 is not prime. So we can skip numbers that are less than or equal to 1.
But what if the list contains non-positive numbers? We can skip them because they cannot be prime (except 2 is the smallest prime). Also note that the sum of digits for a negative number? We can take absolute value for digit sum? But the problem says "number" and typically we consider positive integers for prime. Let's assume the input list contains only positive integers? The problem statement says "list of integers", but in the context of primes, we consider positive. So we can ignore negative numbers and also numbers <=1.
However, to be safe, we can check: if the number is less than 2, then skip.
Steps for the main function:
lucky_numbers = []
for num in list:
if num < 2: continue
if is_prime(num) and is_prime(sum_of_digits(num)):
lucky_numbers.append(num)
But note: the sum of digits of a number like 11 is 1+1=2, which is prime. And 11 is prime, so 11 is lucky.
Let's write the helper functions:
is_prime(n):
if n < 2: return False
if n == 2: return True
if n % 2 == 0: return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
sum_of_digits(n):
We can convert to string and sum each digit, but note that for negative? We are only considering positive, so it's fine.
Alternatively, we can do:
s = 0
while n:
s += n % 10
n //= 10
return s
But note: if n is 0? Then the while loop would not run and return 0. But 0 is not prime, so it's okay.
However, what if the number is 0? Then we skip because 0<2. So we are safe.
But wait: what about the number 2?
is_prime(2) -> True
sum_of_digits(2) -> 2, which is prime -> so 2 is lucky.
But note: the sum of digits of 2 is 2, which is prime. So 2 is lucky.
However, let's check 3:
sum_of_digits(3)=3 -> prime -> lucky.
5: sum=5 -> prime -> lucky.
7: sum=7 -> prime -> lucky.
11: sum=2 -> prime -> lucky.
13: sum=4 -> not prime -> not lucky.
So we have to be careful.
Implementation:
Let's code accordingly.
However, note that the list might be large? We might want to optimize the prime checking by caching? But the numbers in the list can be arbitrary. Alternatively, we can precompute primes up to the maximum number in the list? But the list might have large numbers. Also, the sum of digits is at most (for a number with d digits) 9*d. So if the number is very large, the sum of digits might be much smaller. But we have to check two numbers: the number itself and the sum of digits.
Since we don't know the range, we can do:
max_num = max(list) but note: we are only considering numbers in the list. But the sum of digits of the maximum number might be small. However, we are checking two separate numbers: the number and its digit sum.
We can precompute primes up to max_num and also up to the maximum possible digit sum? The maximum digit sum for a number n is at most 9 * floor(log10(n)+1). So for a number like 10^6, the digit sum is at most 9*7=63. So we can precompute primes up to max_num and also up to, say, 9 * (number of digits in max_num). But note: the digit sum of the maximum number might be less than the maximum number. However, we are also checking the number itself which might be large.
Alternatively, we can do:
Step 1: Find the maximum number in the list (only considering numbers >=2). Let's call it M.
Step 2: Precompute a boolean list for primes up to M (using sieve) and also up to the maximum digit sum we might encounter? But note: the digit sum of a number in the list can be at most 9 * (number of digits in M). So we can compute that maximum digit sum, say D_max, and then precompute primes up to max(M, D_max). But wait: we are checking two separate numbers. The number itself (which is at most M) and the digit sum (which is at most D_max). So we can precompute primes up to max(M, D_max). However, note that D_max might be much smaller than M. But if M is very large, then the sieve for M might be expensive. So maybe we don't want to do a sieve for a very large M.
Alternatively, we can check each number for primality without precomputation? But if the list is long and numbers are large, that might be slow.
Let's consider: the list might have up to, say, 10^5 numbers? And each number might be up to 10^6? Then doing trial division for each number (and for the digit sum) might be acceptable because the digit sum is at most 54 (for 10^6, 9*6=54). But for the number itself, we do trial division up to sqrt(n). For n=10^6, sqrt=1000. So 1000 divisions per number? And we have 10^5 numbers? That would be 10^8 divisions, which might be acceptable in C++ but in Python might be borderline.
Alternatively, we can precompute primes up to the maximum number in the list (if the maximum is not too big) using sieve. But if the maximum is 10^6, then sieve up to 10^6 is fast.
However, the problem does not specify constraints. So we have to design a solution that is efficient for typical inputs.
Let's assume that the list can have up to 10^4 numbers and each number up to 10^6. Then:
Option 1: Precompute primes up to 10^6 (which is 1e6, sieve in O(n log log n) and then we have O(1) prime checks). Also, the digit sum maximum for 10^6 is 54, so we can precompute primes up to 54 (which is trivial). So we can do:
max_num = max(nums) if nums else 0
if max_num < 2: then no primes.
Let M = max_num
Let D_max = 9 * len(str(M)) # but note: the number might be negative? We are taking absolute? But we only consider positive. So for M, we take the number of digits of M.
But note: the digit sum of a number is at most 9 * (number of digits). So we can compute:
max_digit_sum = 0
for num in nums:
if num >= 2:
# we can compute the digit sum for each? But that would be the same as the maximum digit sum we might encounter? Actually, the maximum digit sum for any number in the list is at most 9 * (max_digits). But the maximum digit sum might be from a number that is not the maximum? For example, 999999 has digit sum 54, but 1000000 has digit sum 1. So we can compute:
# We can compute the maximum possible digit sum for numbers in the list by: 9 * (max number of digits in the list). But note: the number of digits in a number n is floor(log10(n))+1. So we can compute:
# Alternatively, we can just compute the digit sum for each number and then take the maximum? But that would be the same as the maximum digit sum we need to check.
However, we are going to check the digit sum for each number anyway. So we can compute the maximum digit sum among the numbers in the list? But we are also going to check the primality of that digit sum. So we need to know up to which number we need to precompute primes? Actually, we need primes up to the maximum of (the numbers in the list and the digit sums of the numbers in the list). Because we check:
is_prime(num) and is_prime(digit_sum)
So we need to know for each number in the list (that is >=2) and for its digit sum, whether they are prime.
We can do:
Step 1: Collect all numbers that are >=2.
Step 2: Compute the set of all numbers we need to check for primality:
S = { num for num in nums if num>=2 } ∪ { digit_sum(num) for num in nums if num>=2 }
Step 3: Let M = max(S) if S is not empty, else 0.
Step 4: Precompute primes up to M using sieve.
Step 5: Then for each num in nums (that is >=2):
if prime[num] and prime[digit_sum(num)]:
then it's lucky.
But note: the digit sum might be 1? Then 1 is not prime, so we don't need to check. But we are including it in S? Then we would have prime[1] which should be false. So we have to set prime[1]=False.
Alternatively, we can precompute primes up to M and then just check.
However, if the list is very large and the numbers are very large, then M might be too big for sieve. But if the numbers are up to 10^6, then sieve up to 10^6 is acceptable.
But what if the list contains a number like 10^9? Then M would be 10^9 and we cannot sieve up to 10^9 in Python easily (memory and time). So we have to consider the constraints.
Given that the problem does not specify, let's assume that the numbers are within a reasonable range for which we can do trial division for each number individually? Or we can use a precomputation for the digit sums? But note: the digit sum is at most 9*10 (for 10^9, 9*10=90) so we only need primes up to 90 for the digit sums. But the number itself might be up to 10^9, then we cannot sieve up to 10^9.
So we have two cases:
Case 1: The maximum number in the list is not too big (say <= 10^6) -> we can sieve.
Case 2: The maximum number is big -> we do trial division for each number.
But note: the digit sum is small, so we can precompute primes up to, say, 1000 (which covers the digit sum for any number with up to 111 digits? Actually 9*111=999, so 1000 is enough). But the number itself might be huge.
Alternatively, we can do:
For each number in the list:
if num < 2: skip.
else:
check if num is prime by trial division (up to sqrt(num)).
compute digit_sum and check if that is prime (by trial division, but digit_sum is small so it's fast).
This way we don't need to precompute for the large numbers.
But if the list has many large numbers, then trial division for each (up to sqrt(num)) might be expensive.
However, note that the digit sum is at most 9 * (number of digits). For a number with 10^9, the digit sum is at most 81 (for 999,999,999 -> 9*9=81). So we only need to check the digit sum for primality up to 81, which is fast.
So we can write:
def is_prime(n):
if n < 2: return False
if n == 2: return True
if n % 2 == 0: return False
i = 3
while i*i <= n:
if n % i == 0:
return False
i += 2
return True
Then for each number in the list:
if num >=2 and is_prime(num) and is_prime(sum_of_digits(num)):
add to result.
But note: the sum_of_digits for a negative number? We are only considering num>=2, so positive.
However, what if the list contains very large numbers? The trial division for a number like 10^12 would require up to 10^6 iterations? That might be too slow for many numbers.
We have to consider the constraints. Since the problem doesn't specify, I'll assume that the numbers are within a range that trial division up to sqrt(n) is acceptable (maybe up to 10^6 or 10^7). But if the list has 10^5 numbers and each number is around 10^6, then the total operations for trial division would be 10^5 * sqrt(10^6) = 10^5 * 1000 = 10^8, which might be acceptable in C++ but in Python might be a bit slow.
Alternatively, we can use the Miller-Rabin test for the large numbers? But that's more complex.
Given the problem statement, let's stick to simple trial division and hope the numbers are not too large.
But note: the problem says "list of integers", so we don't know.
We can do:
Let's define:
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# check up to sqrt(n)
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
This will work for n up to about 10^12 in reasonable time? Actually, for 10^12, sqrt is 10^6, and we are checking only odd numbers so about 500,000 iterations. That might be acceptable for a few numbers but not for 10^5 numbers.
So we need to optimize.
Alternatively, we can precompute primes up to the square root of the maximum number? But note: we are checking each number individually. We can precompute primes up to sqrt(max_num) and then use those primes to check? But then we have to generate primes up to sqrt(max_num). If max_num is 10^12, then sqrt is 10^6, which is feasible with sieve.
Steps for optimized version:
Let M = max(nums) (only considering nums>=2)
Let sqrt_M = int(M**0.5) + 1
Precompute primes up to sqrt_M using sieve -> call this primes_list.
Then for each number n in nums (n>=2):
Check if n is prime by testing divisibility by the primes in primes_list until we reach sqrt(n) (or until we find a divisor). But note: we have primes up to sqrt_M, which is >= sqrt(n) for any n<=M. So we can use the entire primes_list (but we don't need to check primes that are greater than sqrt(n)). So we can iterate over primes in primes_list and stop when prime > sqrt(n).
However, if we precomputed primes up to sqrt_M, then for each n we have to iterate over the primes that are <= sqrt(n). The number of primes up to 10^6 is about 78,498. So for each n, we might check up to about 78,000 primes? But we can break early if we find a divisor. And also, we can break when the prime exceeds sqrt(n). So on average, we might check fewer.
But if we have 10^5 numbers, and for each we might check up to 78,000 primes? That's 7.8e9 checks, which is too many.
So maybe we don't want to do that.
Alternatively, we can use the precomputed primes to check only the numbers that are in the list? But note: the list might have duplicates? We can use memoization? But the numbers might be unique.
Given the complexity, and since the problem doesn't specify constraints, I'll go with the simple trial division for each number, but with a twist: we can cache the results for numbers we've already checked? Because the same number might appear multiple times? But the list might not have duplicates.
Alternatively, we can do:
Let S = set of numbers we need to check (both the numbers and their digit sums). Then we can precompute a dictionary for is_prime for each number in S.
How to precompute for a set S? We can:
Let T = set()
for num in nums:
if num >=2:
T.add(num)
T.add(sum_of_digits(num))
Then for each n in T, check if n is prime (by trial division) and store in a dictionary.
Then for each num in nums:
if num>=2 and prime_dict[num] and prime_dict[sum_of_digits(num)]:
then lucky.
This way we only check each distinct number (and digit sum) once.
But note: the set T might be large if the list is large and all numbers are distinct? But the digit sums are small (at most 9 * max_digits). So T is at most 2 * len(nums) but the digit sums are bounded by a small number (for example, if the numbers are up to 10^9, then digit sum <= 81). So the set T will have at most len(nums) + 1 (for the digit sums, but the digit sums might repeat). So it's efficient.
However, the numbers in the list might be large (like 10^12) and we have to check each one for primality by trial division? But we are only checking each distinct number once. So if the list has 10^5 distinct numbers, we do 10^5 trial divisions? And each trial division for a number up to 10^12 would be sqrt(10^12)=10^6, which is 500,000 iterations (only odd). So 10^5 * 500,000 = 50e9, which is too many.
So we need a better way for large numbers.
Given the complexity, and without constraints, I think we should assume that the numbers are not extremely large (say up to 10^6). Then trial division for each number (or for each distinct number) is acceptable.
But if the numbers are up to 10^6, then sqrt is 1000, and 10^5 * 1000 = 10^8, which is acceptable in Pyton? Maybe in Pyton 10^8 simple operations might take a few seconds.
So I'll write the solution that:
Option 1: Precompute primes up to the maximum number in the list (if the maximum is not too big, say <= 10^6) using sieve, and then for each number we check in O(1). Also precompute primes up to the maximum digit sum (which is small). But note: the maximum number might be 10^6, then sieve up to 10^6 is fast.
How to decide? We can check the maximum number. If the maximum number is <= 10^6, then do sieve. Otherwise, do trial division for each distinct number.
But note: the digit sum is at most 9 * (number of digits in the maximum number). For 10^6, that's 9*6=54. So we can precompute primes up to 54 easily.
However, if the maximum number is 10^7, then sieve up to 10^7 might be acceptable? It depends on memory. 10^7 booleans is about 10MB, which is acceptable.
But if the maximum number is 10^8, then 100MB? Might be acceptable but slower.
Let's set a threshold, say 10^6. If max_num <= 10^6, then sieve. Otherwise, we do trial division for each number (or for the set of distinct numbers) but we can also try to use a precomputation for the digit sums (which are small) and for the numbers we can use trial division with a precomputed list of primes up to sqrt(max_num). But then we are back to the same issue: if max_num is 10^12, then sqrt is 10^6, and we can precompute primes up to 10^6 (which is 78,000 primes) and then for each number we test divisibility by these primes. That would be 78,000 per number? But we can break early. And we have 10^5 numbers? Then 10^5 * 78,000 = 7.8e9, which is too many.
So for large numbers, we might have to use Miller-Rabin? But the problem doesn't require that.
Given the ambiguity, I'll write a solution that uses trial division for each number (without caching) and hope that the input is not too large. But note: if the same number appears multiple times, we are checking it multiple times. So we can cache the results for each number (and for the digit sums) in a dictionary.
Let me write:
def lucky_numbers(nums):
# We'll create a cache for is_prime results for numbers we've checked.
prime_cache = {}
def is_prime(n):
if n in prime_cache:
return prime_cache[n]
if n < 2:
prime_cache[n] = False
return False
if n == 2:
prime_cache[n] = True
return True
if n % 2 == 0:
prime_cache[n] = False
return False
i = 3
while i * i <= n:
if n % i == 0:
prime_cache[n] = False
return False
i += 2
prime_cache[n] = True
return True
def digit_sum(n):
s = 0
n = abs(n) # in case of negative, but we are only considering n>=2, but just in case.
while n:
s += n % 10
n //= 10
return s
result = []
for num in nums:
if num < 2:
continue
ds = digit_sum(num)
if is_prime(num) and is_prime(ds):
result.append(num)
return result
This caches the results for each number and for each digit sum. But note: the digit sum might be the same for many numbers, so caching helps.
However, the cache for is_prime might grow to the number of distinct numbers (and digit sums) in the list. That's acceptable.
But what about the trial division for very large numbers? We are still doing trial division up to sqrt(n) for each distinct large number. If there are many distinct large numbers, it might be slow.
Without knowing constraints, this is a reasonable solution.
Let's test with a small example.
Example: [2, 3, 5, 7, 11, 13, 17, 19, 23]
Lucky numbers:
2: prime, digit sum=2 -> prime -> lucky.
3: prime, digit sum=3 -> prime -> lucky.
5: prime, digit sum=5 -> prime -> lucky.
7: prime, digit sum=7 -> prime -> lucky.
11: prime, digit sum=2 -> prime -> lucky.
13: prime, digit sum=4 -> not prime -> not lucky.
17: prime, digit sum=8 -> not prime -> not lucky.
19: prime, digit sum=10 -> not prime -> not lucky.
23: prime, digit sum=5 -> prime -> lucky.
So expected: [2,3,5,7,11,23]
But wait, 23: 2+3=5 -> prime, so yes.
Let's run the code with this list.
However, note that 1 is not prime, so if we have 1 in the list, we skip.
Also, negative numbers: we skip because num<2.
What about 0? Skip.
What about 1? Skip.
So the function should work.
But note: the problem says "list of integers", so we might get negative numbers? We skip them because they are <2.
However, what about the number 2? It's >=2, so we check.
Let's code accordingly.
But wait: the digit sum of a negative number? We are taking absolute value in digit_sum? But then for negative numbers, we skip because num<2? Actually, negative numbers are less than 2, so we skip. So we don't need to take absolute in digit_sum? But if we have a negative number that is >=2? That's impossible because negative numbers are less than 2. So we are safe.
However, if we have a negative number that is -2? Then -2 < 2, so we skip.
So we don't need to worry.
But in the digit_sum function, if we pass a negative number (which we won't because we skip num<2) then we take absolute. But it's safe.
Let's adjust: in the main loop, we only consider num>=2. So we don't need to handle negative in digit_sum? But what if the list contains a negative number that is, say, -11? Then we skip because -11<2. So we are safe.
However, if we have a number like 2, we pass 2 to digit_sum, which is positive.
So the digit_sum function can be:
def digit_sum(n):
s = 0
while n:
s += n % 10
n //= 10
return s
But wait: if n is negative, then n%10 might be negative? In Python, for negative numbers, modulo returns a positive remainder? Actually:
>>> -11 % 10
9
So if we have a negative number, the digit sum would be computed with negative? But we are skipping negative numbers, so it's okay.
Alternatively, we can do:
n = abs(n)
to be safe. But since we are only passing numbers >=2, it's not necessary.
I'll leave it as:
def digit_sum(n):
s = 0
n = abs(n) # to handle any integer, but we are only using for n>=2, but just in case.
while n:
s += n % 10
n //= 10
return s
Now, let's code accordingly.
But note: what about n=0? Then the while loop doesn't run and returns 0. But we skip n<2, so we won't call digit_sum(0). So it's safe.
Let's write the function.
However, the problem says "write a function". So we'll write:
def find_lucky_numbers(nums):
...
and return the list of lucky numbers.
We'll use the caching approach.
But note: the cache might grow with the distinct numbers. If the list has 10^5 distinct numbers, then the cache will have 10^5 entries. That's acceptable.
Let's code accordingly.
However, if the numbers are very large (like 10^18) then the trial division might be too slow. But without constraints, we assume that the numbers are within a reasonable range.
Alternatively, we can use a faster primality test for large numbers? But the problem doesn't specify.
Given the time, I'll write the simple version and explain that for very large numbers we might need a more efficient primality test.
Code:
Let me write the function with caching.
But note: the digit sum is at most 9*19 (for 64-bit integers, 9*19=171) so we can precompute primes up to 200? But the numbers themselves might be large.
Actually, we can precompute primes up to 200 for the digit sums? But then for the numbers, we still have to check.
So I think the caching with trial division is acceptable for typical inputs.
Let's write the code.</think>
To solve this problem, we need to find all "lucky numbers" in a given list of integers. A lucky number is defined as a number that is prime and whose sum of digits is also prime.
Approach
-
Prime Check: We need a helper function is_prime(n) to determine if a number n is prime. This function efficiently checks for primality by:
- Returning
False if n is less than 2.
- Returning
True if n is 2.
- Returning
False if n is even and greater than 2.
- Checking divisibility by odd numbers up to the square root of
n.
-
Digit Sum Calculation: Another helper function digit_sum(n) computes the sum of the digits of n by repeatedly extracting the last digit and adding it to a running total.
-
Filter Lucky Numbers: Iterate through each number in the input list:
- Skip numbers less than 2 since they cannot be prime.
- For each remaining number, check if both the number and its digit sum are prime using the helper functions.
- Collect all numbers that satisfy both conditions.
Solution Code
def find_lucky_numbers(nums):
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
def digit_sum(n):
s = 0
n = abs(n)
while n:
s += n % 10
n //= 10
return s
result = []
for num in nums:
if num < 2:
continue
ds = digit_sum(num)
if is_prime(num) and is_prime(ds):
result.append(num)
return result
Explanation
-
Prime Check (is_prime):
- The function first handles base cases: numbers less than 2 are not prime, 2 is prime, and even numbers greater than 2 are not prime.
- For odd numbers greater than 2, it checks divisibility by every odd number from 3 up to the square root of
n. If any divisor is found, n is not prime.
-
Digit Sum (digit_sum):
- The absolute value of
n is taken to handle any negative inputs (though the main loop skips numbers <2).
- The sum is computed by repeatedly taking the last digit (
n % 10) and then removing that digit (n //= 10).
-
Main Loop:
- For each number in the input list, skip if it's less than 2.
- Compute the digit sum of the number.
- Check if both the number and its digit sum are prime. If so, add the number to the result list.
This approach efficiently checks each number and its digit sum for primality, ensuring optimal performance for typical input sizes. The solution handles edge cases such as negative numbers and zero by skipping them early.