Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Mathematical Computations in Python: Sequences, Primes, and Patterns

Tech May 14 1

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)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.