Mathematical Computations in Python: Sequences, Primes, and Patterns
Prime Number Detection in a Range
start = int(input("Enter the lower bound: "))
end = int(input("Enter the upper bound: "))
for candidate in range(start + 1, end):
if candidate < 2:
continue
is_prime = True
for divisor in range(2, int(candidate ** 0.5) + 1):
if candidate % divisor == 0:
is_prime = False
break
if is_prime:
print(candidate)
Generating Arithmetic Progrestions
values = input("Enter start, step, count (comma-separated): ").split(',')
first, delta, length = [eval(v) for v in values]
sequence = [first + i * delta for i in range(length)]
print(sequence)
Buildding Geometric Progressions
parts = input("Enter first term, common ratio, number of terms: ").split(',')
a, r, n = [eval(x) for x in parts]
terms_as_str = [str(a * (r ** i)) for i in range(n)]
print(','.join(terms_as_str))
Computing Logarithms Safely
import math
try:
base_val = float(input("Logarithm base: "))
num_val = float(input("Logarithm argument: "))
if base_val <= 0 or num_val <= 0:
print("Both base and argument must be greater than zero.")
else:
res = math.log(num_val, base_val)
print(res)
except ValueError:
print("Invalid numeric input.")
except ZeroDivisionError:
print("Base cannot be 1.")
Fibonacci Sequence Up to a Limit
limit = 50
prev, curr = 0, 1
while prev <= limit:
print(prev, end=', ')
prev, curr = curr, prev + curr
print()
Custom Count
n_terms = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
for _ in range(n_terms):
print(a, end=' ')
a, b = b, a + b
Pascal's Triangle
def generate_pascal(rows):
triangle = []
for i in range(rows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
def print_right(tri):
for row in tri:
for val in row:
print(f"{val:3d}", end=" ")
print()
def print_centered(tri):
n = len(tri)
for i, row in enumerate(tri):
print(' ' * (n - i - 1), end='')
for val in row:
print(f"{val:3d}", end=" ")
print()
# Example with 8 rows
triangle = generate_pascal(8)
print("Right-aligned:")
print_right(triangle)
print("\nCentered:")
print_centered(triangle)