feat: completed exercise 17 and 18
This commit is contained in:
+11
-1
@@ -1,4 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
Write a program to use a loop to find the factorial of a given number (e.g., 5!). The factorial of N is the product
|
Write a program to use a loop to find the factorial of a given number (e.g., 5!). The factorial of N is the product
|
||||||
of all integers from 1 to N.
|
of all integers from 1 to N.
|
||||||
"""
|
"""
|
||||||
|
# Set input number and factorial variables
|
||||||
|
num = 5
|
||||||
|
factorial = 1
|
||||||
|
|
||||||
|
# Iterate through range of 1 to num var + 1 and multiply by i
|
||||||
|
for i in range(1, num + 1):
|
||||||
|
factorial = factorial * i
|
||||||
|
|
||||||
|
# Print resulting factorial
|
||||||
|
print(factorial)
|
||||||
|
|||||||
+18
-1
@@ -2,4 +2,21 @@
|
|||||||
The Collatz conjecture states that if you start with any positive integer n, and if n is even, divide it by 2; if n is
|
The Collatz conjecture states that if you start with any positive integer n, and if n is even, divide it by 2; if n is
|
||||||
odd, multiply it by 3 and add 1. Repeat the process. The sequence will always eventually reach 1. Write a program to
|
odd, multiply it by 3 and add 1. Repeat the process. The sequence will always eventually reach 1. Write a program to
|
||||||
print this sequence for a given number.
|
print this sequence for a given number.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# set variable n to 6
|
||||||
|
n = 6
|
||||||
|
|
||||||
|
# Runs the loop until n = 1, signifying the end of the Collatz conjecture
|
||||||
|
while n != 1:
|
||||||
|
# print value of n plus a comma and space to print on the same line
|
||||||
|
print(n, end=", ")
|
||||||
|
# if n is even, halve n
|
||||||
|
if n % 2 == 0:
|
||||||
|
n = n // 2
|
||||||
|
# if n is odd, multiply by 3 and add one
|
||||||
|
else:
|
||||||
|
n = n * 3 + 1
|
||||||
|
|
||||||
|
# Prints final value for n, which should always be 1
|
||||||
|
print(n)
|
||||||
Reference in New Issue
Block a user