Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
3 and 7 in Python
Sometimes we need to determine if a positive number can be expressed as a sum of non-negative multiples of 3 and 7. This problem involves checking if n = a×3 + b×7 where a and b are non-negative integers.
For example, 13 can be written as 1×7 + 2×3 = 13, so the answer is True.
Algorithm
The approach is to iterate through all possible multiples of 7 up to n and check if the remainder is divisible by 3 ?
For each multiple of 7 from 0 to n (step by 7)
Check if
(n - multiple_of_7) % 3 == 0If yes, return True (we found a valid combination)
If no valid combination found, return False
Implementation
class Solution:
def solve(self, n):
for i in range(0, n+1, 7):
if (n - i) % 3 == 0:
return True
return False
# Test the solution
ob = Solution()
print(ob.solve(13))
print(ob.solve(1))
print(ob.solve(10))
True False True
How It Works
Let's trace through the example with n = 13 ?
i = 0: (13 - 0) % 3 = 13 % 3 = 1 ? 0
i = 7: (13 - 7) % 3 = 6 % 3 = 0 ? (Found: 2×3 + 1×7 = 13)
Alternative Direct Function
def can_sum_with_3_and_7(n):
"""Check if n can be expressed as a×3 + b×7"""
for multiples_of_7 in range(0, n+1, 7):
remainder = n - multiples_of_7
if remainder % 3 == 0:
return True
return False
# Test cases
test_numbers = [13, 1, 6, 7, 9, 10, 14]
for num in test_numbers:
result = can_sum_with_3_and_7(num)
print(f"{num}: {result}")
13: True 1: False 6: True 7: True 9: True 10: True 14: True
Time Complexity
The time complexity is O(n/7) since we iterate through multiples of 7 up to n. The space complexity is O(1) as we use constant extra space.
Conclusion
This algorithm efficiently determines if a number can be expressed as a sum of non-negative multiples of 3 and 7. The key insight is iterating through multiples of 7 and checking divisibility by 3 for the remainder.
