The next topic is Prime Number Programs, where we focus on writing programs to identify prime numbers and perform tasks related to prime numbers.
We’ll start with Prime Factorization, which is finding the prime factors of a number. To meet your specific request, I will also include a program that executes a loop until the square of a prime factor.
Prime Number Programs
1. Check If a Number is Prime
Description: This program checks if a number is prime or not.
# Program to check if a number is prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num / 2) + 1):
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
2. Find Prime Factors of a Number
Description: This program finds the prime factors of a given number.
# Program to find prime factors of a number
num = int(input("Enter a number: "))
i = 2
print(f"Prime factors of {num} are:")
while i * i <= num:
if num % i:
i += 1
else:
num //= i
print(i, end=" ")
if num > 1:
print(num)
3. Loop Till the Square of the Prime Factor
Description: This program loops through the prime factors and executes a loop until the square of the prime factor.
# Program to loop until the square of the prime factor
def prime_factors(n):
factors = []
i = 2
while i * i <= n:
if n % i == 0:
factors.append(i)
n //= i
else:
i += 1
if n > 1:
factors.append(n)
return factors
def loop_until_square_of_prime_factor(n):
factors = prime_factors(n)
for factor in factors:
print(f"\nExecuting loop for prime factor {factor}:")
i = 1
# Loop until the square of the prime factor
while i <= factor * factor:
print(f"i = {i}")
i += 1
num = int(input("Enter a number: "))
loop_until_square_of_prime_factor(num)
Explanation
- Prime Factors Program: This program finds the prime factors of a number using a while loop. It divides the number by possible factors until we reach a prime number.
- Loop Until Square of Prime Factor: In this program, we first find the prime factors of the input number, and for each prime factor, we execute a loop that runs until the square of that prime factor. This fulfills your specific requirement.
Let me know if you’d like to explore more prime number programs or move on to the next topic!