Tuesday, August 23, 2022

How to find multiples of 3 and 5 using Python?

Description of the problem: If we list all the natural numbers below 10 that are multiples of 3 or 5 we will get: \begin{eqnarray} 3,5,6,9. \end{eqnarray} The sum of these numbers (3,5,6 and 9) is 23. The idea is to determine all the multiples of 3 and 5 below 1000, below 10000, and below 100000 and calculate the sum. After the initial solution is complete create a program that will find multiples of any two numbers provided by the user and calculate the sum of these multiples.

Solution: Beginner Level

The basic solution will be created without any library, functions, or class (object-oriented program). The basic solution is the solution to the problem in the simplest basic form.

Multiples of 3 and 5 in range from 1 to 10

We will start by creating the program that will return all natural numbers below 10 that are multiples of 3 and 5, and calculate the sum of these numbers. By doing so we will see if our solution can return the numbers specified in the description of the problem. The first step is to define variables to which limit (10), and numbers (3 and 5) will be assigned.
Limit = 10
Mul1 = 3
Mul2 = 5
Besides these three variables, the variable ListNum will be created to which an empty list will be assigned. This list will be used to store the multiples of 3 and 5.
ListNum = []
The second step is to create for loop which will iterate from 1 to 10 (not including 10). For each iteration number, the modulo will be calculated i.e. the remainder of the Euclidean division of iteration numbers by 3 and 5 will be obtained. In mathematical form this can be written as: \begin{eqnarray} i\%3 = ?,\\ i\%5 = ?, \end{eqnarray} where i is the iteration number of the for loop. However, the idea is not just to obtain the modulo, the idea is to see if the division of iteration numbers 3 and 5 will return remainder 0 (no remainder). This condition in mathematical form can be written as: \begin{eqnarray} i \% 3 = 0, \mathrm{or} \quad i \% 5 = 0. \end{eqnarray} If the condition is True for modulo of 3 or 5 the number will be stored in the ListNum list.
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
As seen from the previous code block, the for loop will iterate in the range from 1 to 10 (not including 10) and will save the iteration number in the ListNum list if there is no remainder between the current iteration number and number 3 or 5. After the for loop is completed we want to show these numbers stored in the ListNum list and calculate the sum of these numbers.
print("List of natural numbers that are multiplies of 3 and 5.")
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
The first line in the previous code block will just output the information about the list of natural numbers that are multiples of 3 and 5. This is not the crucial information for this solution. The next print function will display the ListNum list and the final code line will output the sum of that list. The entire code of this example is given below.
Limit = 10
Mul1 = 3
Mul2 = 5
ListNum = []
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
print("List of natural numbers that are multiples of 3 and 5.")
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
Output
List of natural numbers that are multiples of 3 and 5.
[3, 5, 6, 9]
Sum of these numbers is equal to 23
As seen from the obtained results as the output of the program the results are the same as those given in the initial description of the problem.

Multiples of 3 and 5 in range from 1 to 1000/10000 /100000

The solution to this problem will be based on the basic solution created in the previous example. The first difference is that we will give the ability user to type in the limit (1000/ 10000/ 100000). This will be achieved using input built-in function and assigned to variable named Limit. The variables Mul1 and Mult2 will be used from the previous example.
Limit = int(input("Enter a limit number>")
The input provided by the user will be converted from string to integer. The input function will return the user-input value and convert it to a string. This string (number) has to be converted into an integer to be used later in the program. The empty list used to store natural numbers, the for loop, and the print function to show the output will be the same as defined in the previous example.
ListNum = []
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
print("List of natural numbers that are multiplies of 3 and 5.")
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
Output for the user input 1000
Enter a limit number>1000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 995, 996, 999]
Sum of these numbers is equal to 233168
Output for the user input 10000
Enter a limit number>10000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 9995, 9996, 9999]
Sum of these numbers is equal to 23331668
Output for the user input 100000
Enter a limit number>10000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 99993, 99995, 99996, 99999]
Sum of these numbers is equal to 2333316668

Multiples of two custom numbers and in custom range

This program in comparison to previous ones has a couple of modifications. First the numbers 3 and 5 are replaced by the user-defined numbers which means we have to implement built-in functions input and int. The input function will return a string of what was typed by the user, and int function will convert the string to an integer which will be used later. The limit number which will be used to define a range in which the multiplies are searched is the same as in the previous example.
Limit = int(input("Enter a limit number>")
Mul1 = int(input("Enter the first number>")
Mul2 = int(input("Enter a second number>")
ListNum = []
The for loop is the same as in previous cases.
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
The last three lines of code that will show the output are slightly changed. In the first print function, we will use the format built-in function to insert custom numbers (defined by the user) and insert them into a string. The remaining two lines of code (print functions that show the list of numbers and the sum of these numbers) are the same as in previous examples.
print("List of natural numbers that are multiplies of {} and {}.".format(Mul1, Mul2))
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
The entire code used in this example is given below.
Limit = int(input("Enter a limit number>")
Mul1 = int(input("Enter the first number>")
Mul2 = int(input("Enter a second number>")
ListNum = []
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
print("List of natural numbers that are multiples of {} and {}.".format(Mul1, Mul2))
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
Output #Test1
Enter a limit number>2500
Enter the first number>25
Enter a second number>50
List of natural numbers that are multiplies of 25 and 50.
[25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525, 550, 575, 600, 625, 650, 675, 700, 725, 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725, 1750, 1775, 1800, 1825, 1850, 1875, 1900, 1925, 1950, 1975, 2000, 2025, 2050, 2075, 2100, 2125, 2150, 2175, 2200, 2225, 2250, 2275, 2300, 2325, 2350, 2375, 2400, 2425, 2450, 2475]
Sum of these numbers is equal to 123750

The problem with this program is that if we type a string (multiple characters) when asked to define a limit, first, and the second number the ValueError will be raised. The reason is that the typed characters cannot be converted to the integer type. To overcome this problem we will use a while loop with try-except.
while True:
try:
Limit = int(input("Enter a limit number>"))
Mul1 = int(input("Enter the first number>"))
Mul2 = int(input("Enter a second number>"))
break
except ValueError:
print("Input Error. Try again.")
continue
Every time we typed characters instead of numbers the program will handle the ValueError with except statement i.e. it will print out "Input Error. Try again." The rest of the program is given below.
ListNum = []
for i in range(1,Limit,1):
if i%Mul1 == 0 or i%Mul2 == 0:
ListNum.append(i)
print("List of natural numbers that are multiples of {} and {}.".format(Mul1, Mul2))
print("{}".format(ListNum))
print("Sum of these numbers is equal to {}".format(sum(ListNum)))
Output:
Enter a limit number>2500
Enter the first number>25
Enter a second number>50d
Input Error. Try again.
Enter a limit number>2500
Enter the first number>25
Enter a second number>50
List of natural numbers that are multiplies of 25 and 50.
[25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525, 550, 575, 600, 625, 650, 675, 700, 725, 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725, 1750, 1775, 1800, 1825, 1850, 1875, 1900, 1925, 1950, 1975, 2000, 2025, 2050, 2075, 2100, 2125, 2150, 2175, 2200, 2225, 2250, 2275, 2300, 2325, 2350, 2375, 2400, 2425, 2450, 2475]
Sum of these numbers is equal to 123750

Solution: Intermediate Level

So far we have created the program that will give the multiples of custom (user-defined) numbers in a custom range, and in the end, calculate the sum of these multiples. The next step is to formulate the program using functions. The first step is to create a program with a function that will generate the results defined in the description of the problem (multiples of 3 and 5 for all natural numbers under 10).

Multiples of 3 and 5 for all natural numbers under 10

At this stage program for finding multiples of 3 and 5 for all natural numbers under 10 will be created using Python functions. Three functions will be created and these are InputVariables, MultiplesList, and displayResults. The InputVariables is a function that contains the definition of variables to which numbers 3 and 5 were assigned, and of course limit (10) up to which multiples of 3 and 5 will be searched. These three variables will be the outputs of the function InputVariables. It should be noted that this function does not require any input argument.
def InputVariables():
Limit = 10
Mul1 = 3
Mul2 = 5
return Limit, Mul1, Mul2
Limit, Mul1, Mul2 = InputVariables()
In the last line of code from the previous code block we have called the function InputVariables() and since this function returns three variables the call of this function requires three variables to which these tree values will be assigned.
The next step is to create function MultiplesList that will be used to create the list in which all natural numbers that are multiples of 3 and 5 up to a specific number in this case 10 will be stored. To create list of multiples the function MultiplesList will require three arguments (Limit, Mul1, and Mul2) and these arguments were created using function InputVariables(). The Limit argument will be used in for loop as the upper bound of the range function. For each iteration inside the for loop, the modulo will be calculated i.e. iteration number mod 3 and iteration number mod 5. If one of these modulo calculations is equal to 0 (no remainder) then the iteration number will be appended to a list.
def InputVariables():
Limit = 10
Mul1 = 3
Mul2 = 5
return Limit, Mul1, Mul2
def MultiplesList(limit, mul1, mul2):
ListNum = []
for i in range(1,limit,1):
if i%mul1 == 0 or i%mul2 == 0:
ListNum.append(i)
return ListNum
Limit, Mul1, Mul2 = InputVariables()
listNum = MultiplesList(Limit, Mul1, Mul2)
In previous block of code we have shown the definition of MultiplesList(limit, mul1, mul2) function with the code for calling this function alongside already existing code i.e. the InputVariables() function. As seen in MultiplesList function before the for loop the ListNum variable is created to which an empty list is assigned. This list will be used to store all natural numbers that are multiples of 3 and 5 in the range from 1 to 10. In the last line of code the function MultiplesList is called. Since this function has only one return value only one variable (listNum) is equal to the function call. This means that the return value of MultiplesList will be assigned to the listNum variable.
The final function that will be created displayResults has no return variable. This function consists of a print built-in function which means each time the displayResults function is called it will show as output strings inside the print functions. The function displayResults will require three arguments and these are:
  • listNum - the list of multiples of 3 and 5 created using MultiplesList function and
  • mul1 and mul2 - numbers 3 and 5 created using InputVariablesfunction.
The entire code with displayResults function is given below.
def InputVariables():
Limit = 10
Mul1 = 3
Mul2 = 5
return Limit, Mul1, Mul2
def MultiplesList(limit, mul1, mul2):
ListNum = []
for i in range(1,limit,1):
if i%mul1 == 0 or i%mul2 == 0:
ListNum.append(i)
return ListNum
def displayResults(listNum, mul1, mul2):
print("List of natural numbers that are multiplies of {} and {}.".format(mul1,mul2))
print("{}".format(listNum))
print("Sum of these numbers is equal to {}".format(sum(listNum)))

Limit, Mul1, Mul2 = InputVariables()
listNum = MultiplesList(Limit, Mul1, Mul2)
displayResults(listNum, Mul1, Mul2)
As seen from previous block of code the displayResults function will display the string "List of natural numbers that are multiples of {}} and {}.". The "{}" are used for the format function to insert 3 and 5 numbers inside. The next print function is used to show the list of selected natural numbers that are multiples of 3 and 5. The final print function is used to show as output the sum of the numbers in the list listNum. The string "Sum of these numbers is equal to {}" contains {} which is a place where the argument of the format function will be placed. Inside the format function the sum built-in Python function is used which will calculate the sum of all members inside the listNum list. As already discussed since displayResults function does not return any value (only displays the strings) the function call is pretty simple, all you need to do is type in the function name provided with the right arguments which are in this case listNum, Mul1, and Mul2. This function call is seen in the last code line of the previous code block.
Output:
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9]
Sum of these numbers is equal to 23

Multiples of 3 and 5 for all natural numbers under 1000, 10000, and 100000

To find multiples of 3 and 5 for all natural numbers under 1000, 10000, 100000, or any other number we will modify the InputVariables from the previous example. The input function will be used to ask the user to type in the number. This number will be converted to integer using int function and the number will be assigned to variable name Limit. The code line inside the InputVariables function
Limit = int(input("Enter a limit number> "))
However, we have to create a procedure that will ask the user to type the number again if the user accidentally types a string that cannot be converted to an integer. This will be done using try-except structure.
while True:
try:
Limit = int(input("Enter a limit number> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
The previous code block is used to handle invalid input i.e. string. Without the try-except, if a string was typed then the ValueError will be raised. Since we have the except ValueError instead of raising this error the output will be shown in the print function ("Invalid input. Please try again."). The entire code for this example is given below.
def InputVariables():
while True:
try:
Limit = int(input("Enter a limit number> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
Mul1 = 3
Mul2 = 5
return Limit, Mul1, Mul2
def MultiplesList(limit, mul1, mul2):
ListNum = []
for i in range(1,limit,1):
if i%mul1 == 0 or i%mul2 == 0:
ListNum.append(i)
return ListNum
def displayResults(listNum, mul1, mul2):
print("List of natural numbers that are multiplies of {} and {}.".format(mul1,mul2))
print("{}".format(listNum))
print("Sum of these numbers is equal to {}".format(sum(listNum)))

Limit, Mul1, Mul2 = InputVariables()
listNum = MultiplesList(Limit, Mul1, Mul2)
displayResults(listNum, Mul1, Mul2)
Output: limit 1000, first try invalid input
Enter a limit number> 1000wq
Invalid input. Please try again.
Enter a limit number> 1000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 993, 995, 996, 999]Sum of these numbers is equal to 233168
Output: limit 1000
Enter a limit number> 1000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 993, 995, 996, 999]
Sum of these numbers is equal to 233168
Output: limit 10000
Enter a limit number> 10000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 9993, 9995, 9996, 9999]
Sum of these numbers is equal to 23331668
Output: limit 100000
Enter a limit number> 100000
List of natural numbers that are multiplies of 3 and 5.
[3, 5, 6, 9, 10,..., 99993, 99995, 99996, 99999]
Sum of these numbers is equal to 2333316668

Multiples of custom two numbers and custom range

The term "custom two numbers" and "custom range" means that all these numbers will be typed by the user. To do this we will use the input and int function. The input function allows user input. This input is a string that has to be converted to an integer using int function. To avoid ValueError in case the user types something that is not a number we will use try and except structre that was explained previously. All these inputs (custom two numbers and custom range (limit)) are defined in InputVariables() function. The entire code is given below.
def InputVariables():
while True:
try:
Limit = int(input("Enter a limit number> "))
Mul1 = int(input("Enter the first number> "))
Mul2 = int(input("Enter a second number> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
return Limit, Mul1, Mul2
def MultiplesList(limit, mul1, mul2):
ListNum = []
for i in range(1,limit,1):
if i%mul1 == 0 or i%mul2 == 0:
ListNum.append(i)
return ListNum
def displayResults(listNum, mul1, mul2):
print("List of natural numbers that are multiplies of {} and {}.".format(mul1,mul2))
print("{}".format(listNum))
print("Sum of these numbers is equal to {}".format(sum(listNum)))

Limit, Mul1, Mul2 = InputVariables()
listNum = MultiplesList(Limit, Mul1, Mul2)
displayResults(listNum, Mul1, Mul2)
Output: multiples of 5 and 6 to a range 100
Enter a limit number> 100
Enter a first number> 5
Enter the second number> 6
List of natural numbers that are multiplies of 5 and 6.
[5, 6, 10, 12, 15, 18, 20, 24, 25, 30, 35, 36, 40, 42, 45, 48, 50, 54, 55, 60, 65, 66, 70, 72, 75, 78, 80, 84, 85, 90, 95, 96]
Sum of these numbers is equal to 1586

Solution: Advanced Level

The advanced-level solution is created using object-oriented programming. First, we will create a class that will solve the example given in the description of the problem i.e. the sum of the multiples of 3 and 5 in the range from 1 to 10. After confirming that solution we will modify the class and show the sum for multiples of 3 and 5 for natural numbers in the range 1000/ 10000/ 100000. Finally, we will modify the class so we can find multiples of \(m\) and \(n\) where \(m\) and \(n\) are numbers defined by the user.

The multiples of 3 and 5 in range from 1 to 10 (advanced).

The program will be based on the class named Mult3and5.
class Mult3and5():
#ClassBody
This class will contain three methods (functions) and these are __init__, Calculate, and displayRes. The __init__ method (called constructor) is usually used when creating classes to initialize (assign values) to the data members of the class when the object of the class is created. In this case, the __init__ method will initialize limit (10), numbers (3 and 5), and an empty list named listNum which will be used to store the multiples of 3 and 5. These values will be attributes of the object test and we are going to show these values using the print built-in function.
class Multi3and5():
def __init__(self):
self.limit = 10
self.mul1 = 3
self.mul2 = 5
self.listNum = []
test = Mul3and5()
test= Mult3and5()
print("limt = {}".format(test.limit))
print("mul1 = {}".format(test.mul1))
print("mul2 = {}".format(test.mul2))
print("listNum = {}".format(test.listNum))
Output:
limt = 10
mul1 = 3
mul2 = 5
listNum = []
The next method inside the Multi3and5 class is named Calculate. The method is used to find the natural numbers in specific numbers range that are multiples of 3 and 5. To do this the method will require some arguments which were all created using the __init__ constructor (limit, mul1, mul2, and listNum). Inside the method body, a for loop is created which will iterate through numbers in a specific range in this case from 1 to 10. In each iteration, if the iteration number divided by 3 or 5 does not have a remainder i.e. the result of modulus is equal to 0 then the iteration number will be stored in the listNum list. Otherwise, the number will be neglected.
class Multi3and5():
def __init__(self):
self.limit = 10
self.mul1 = 3
self.mul2 = 5
self.listNum = []
def Calculate(self, limit, mul1, mul2, listNum):
for i in range(1, self.limit,1):
if i%self.mul1 == 0 or i%self.mul2 == 0:
self.listNum.append(i)
else: pass
return self.listNum
test = Multi3and5()
print("limt = {}".format(test.limit))
print("mul1 = {}".format(test.mul1))
print("mul2 = {}".format(test.mul2))
print("listNum = {}".format(test.listNum))
res = test.Calculate(test.limit, test.mul1, test.mul2, test.listNum)
print("listNum = {}".format(res))
Output:
limt = 10
mul1 = 3
mul2 = 5
listNum = []
listNum = [3, 5, 6, 9]
The final step is to create a method named displayRes that will be used to display results. To display results this method will require some input arguments that are created using __init__ constructor and Calculate method (mul1, mul2, and listNum). The method will consist of three print built-in functions used to show the output. The first print function is used to display a "List of natural numbers that are multiples of {} and {}". The "{}" in the string are used with the format function to insert mul1 and mul2 values, respectively. The second print function is used to show the filled listNum list i.e. the list created and assigned to the res variable. The third and final print function is used to display the "Sum of these numbers is equal to {}". The "{}" is used with format function to insert the value of sum(self.listNum) i.e. the sum of all elements inside the listNumber list.
class Multi3and5():
def __init__(self):
self.limit = 10
self.mul1 = 3
self.mul2 = 5
self.listNum = []
def Calculate(self, limit, mul1, mul2, listNum):
for i in range(1, self.limit,1):
if i%self.mul1 == 0 or i%self.mul2 == 0:
self.listNum.append(i)
else: pass
return self.listNum
def displayRes(self, mul1, mul2, listNum):
print("List of natural numbers that are multiples of {} and {}".format(self.mul1, self.mul2))
print("{}".format(self.listNum))
print("Sum of these numbers is equal to {}".format(sum(self.listNum)))
test= Mult3and5()
res = test.Calculate(test.limit, test.mul1, test.mul2, test.listNum)
test.displayRes(test.mul1, test.mul2, res)
As seen from the previous block of code all print functions outside the class were removed since all the output is handled with displayRes method.
Output:
List of natural numbers that are multiples of 3 and 5.
[3, 5, 6, 9]
Sum of these numbers is equal to 23
As seen from the previous Output all the obtained results match with the results shown in Description of the problem. Now in the next example we will slightly modify the code and show multiples of 3 and 5 for numbers under 1000, 10000, and 100000.

The multiples of 3 and 5 for numbers under 1000, 10000, and 100000 (advanced).

In this example, we will use the code from the previous one and make some modifications to the __init__ constructor. The code self.limit = 10 will be replaced with a while loop in which we will ask a user to type in the number through try-except to handle a ValueError exception. When the object of the Class is created and the program executed the user will be asked to type in a number. If for some reason a character is typed which could not be converted to an integer the ValueError exception that should be raised will be handled by the except block of code that will print out "Invalid input. Please try again.". On the other hand, if all numbers are typed for example 1000 then this will be converted to an integer and the program will continue its execution.
class Multi3and5():
def __init__(self):
while True:
try:
self.limit = int(input("Enter a limit number> "))
break
except:
print("Invalid input. Please try again.")
pass
self.mul1 = 3
self.mul2 = 5
self.listNum = []
def Calculate(self, limit, mul1, mul2, listNum):
for i in range(1, self.limit,1):
if i%self.mul1 == 0 or i%self.mul2 == 0:
self.listNum.append(i)
else: pass
return self.listNum
def displayRes(self, mul1, mul2, listNum):
print("List of natural numbers that are multiples of {} and {}".format(self.mul1, self.mul2))
print("{}".format(self.listNum))
print("Sum of these numbers is equal to {}".format(sum(self.listNum)))
test= Mult3and5()
res = test.Calculate(test.limit, test.mul1, test.mul2, test.listNum)
test.displayRes(test.mul1, test.mul2, res)
Output: limit 1000
Enter a limit number> 100d
Invalid input. Please try again.
Enter a limit number> 1000
List of natural numbers that are multiples of 3 and 5.
[3, 5, 6, 9, 10,..., 993, 995, 996, 999]
Sum of these numbers is equal to 233168
As seen from the output the first time we have typed accidentally a "d" character so the program showed as output "Invalid output. Please try again."
Output: limit 10000
Enter a limit number> 10000
List of natural numbers that are multiples of 3 and 5.
[3, 5, 6, 9, 10,..., 9993, 9995, 9996, 9999]
Sum of these numbers is equal to 23331668
Output: limit 100000
Enter a limit number> 100000
List of natural numbers that are multiples of 3 and 5.
[3, 5, 6, 9, 10,..., 99993, 99995, 99996, 99999]
Sum of these numbers is equal to 2333316668

Multiples of two user-defined numbers in a user-defined range (advanced)

Again in this example, we will re-use the code from the previous example. We will add two more inputs inside the try block that will ask the user to define multiples of two user-defined numbers. To do this we will use two functions i.e. input and int. The input function will be used to ask a user to input the number that is of string type and will be converted to an integer using the int function.
class MultiNamdM():
def __init__(self):
while True:
try:
self.limit = int(input("Enter a limit number> "))
self.mul1 = int(input("Enter a first number> "))
self.mul2 = int(input("Enter the second number> "))
break
except:
print("Invalid input. Please try again.")
pass
self.listNum = []
def Calculate(self, limit, mul1, mul2, listNum):
for i in range(1, self.limit,1):
if i%self.mul1 == 0 or i%self.mul2 == 0:
self.listNum.append(i)
else: pass
return self.listNum
def displayRes(self, mul1, mul2, listNum):
print("List of natural numbers that are multiples of {} and {}".format(self.mul1, self.mul2))
print("{}".format(self.listNum))
print("Sum of these numbers is equal to {}".format(sum(self.listNum)))
test= MultiNamdM()
res = test.Calculate(test.limit, test.mul1, test.mul2, test.listNum)
test.displayRes(test.mul1, test.mul2, res)
Output:
Enter a limit number> 200
Enter a first number> 5
Enter the second number> 7
List of natural numbers that are multiplies of 5 and 7.
[5, 7, 10, 14,..., 190, 195, 196]
Sum of these numbers is equal to 6217

No comments:

Post a Comment