Python: Find four positive even integers whose sum is n
Four Even Integers Summing to n
Write a Python program to find four positive even integers whose sum is a given integer.
Input: n = 100 Output: [94, 2, 2, 2] Input: n = 1000 Output: [994, 2, 2, 2] Input: n = 10000 Output: [9994, 2, 2, 2] Input: n = 1234567890 Output: [1234567884, 2, 2, 2]
Sample Solution:
Python Code:
# License: https://bit.ly/3oLErEI
# Function to find four positive even integers whose sum is equal to a given number
def test(n):
# Iterate over possible values for the first even integer (a)
for a in range(n, 0, -1):
# Skip odd values for a
if not a % 2 == 0:
continue
# Iterate over possible values for the second even integer (b)
for b in range(n - a, 0, -1):
# Skip odd values for b
if not b % 2 == 0:
continue
# Iterate over possible values for the third even integer (c)
for c in range(n - b - a, 0, -1):
# Skip odd values for c
if not c % 2 == 0:
continue
# Iterate over possible values for the fourth even integer (d)
for d in range(n - b - c - a, 0, -1):
# Skip odd values for d
if not d % 2 == 0:
continue
# Check if the sum of a, b, c, and d equals the target number
if a + b + c + d == n:
# Return the list of found even integers
return [a, b, c, d]
# Test cases with different values of n
n = 100
print("Four positive even integers whose sum is", n)
print(test(n))
n = 1000
print("\nFour positive even integers whose sum is", n)
print(test(n))
n = 10000
print("\nFour positive even integers whose sum is", n)
print(test(n))
n = 1234567890
print("\nFour positive even integers whose sum is", n)
print(test(n))
Sample Output:
Four positive even integers whose sum is 100 [94, 2, 2, 2] Four positive even integers whose sum is 1000 [994, 2, 2, 2] Four positive even integers whose sum is 10000 [9994, 2, 2, 2] Four positive even integers whose sum is 1234567890 [1234567884, 2, 2, 2]
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Expand Spaces.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics