In this post, we are going to find the sum of all composite numbers between two given numbers in Python using a while loop.
In mathematics, a composite number is a positive integer that has at least one positive divisor other than one or itself.
In this programming task, we will write a program that finds the sum of all composite numbers between two given numbers.
Simple code:
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))
composite_sum = 0
for num in range(start, end+1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
composite_sum += num
break
print("The sum of all composite numbers between", start, "and", end, "is:", composite_sum)
Output:
Enter starting number: 5
Enter ending number: 65
The sum of all composite numbers between 5 and 65 is: 1639
Code With Explanation:
# Take input of starting and ending numbers
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))
# Set initial sum to 0
composite_sum = 0
# Loop through all numbers between start and end (inclusive)
for num in range(start, end+1):
# Check if number is greater than 1
if num > 1:
# Loop through all numbers between 2 and the number (exclusive)
for i in range(2, num):
# Check if number is divisible by any number other than 1 and itself
if (num % i) == 0:
# If number is composite, add it to the sum and break the loop
composite_sum += num
break
# Print the sum of all composite numbers between start and end
print("The sum of all composite numbers between", start, "and", end, "is:", composite_sum)
Explanation:
The program takes two input numbers as the starting and ending points of the range to be checked.
It then uses a for loop to loop through all numbers between the starting and ending points (inclusive).
For each number, it checks if the number is greater than 1.
If it is, it loops through all numbers between 2 and the number (exclusive) to check if the number is divisible by any number other than 1 and itself.
If it is, it adds the number to the sum of all composite numbers found so far and breaks the loop.
Finally, it prints the sum of all composite numbers between the starting and ending points.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.