Python Function to Check for Semiprime Numbers
Determine if a Number is Semiprime in Python
This article provides a Python function to determine if a given positive integer is a semiprime number.
What is a semiprime number?
A semiprime number is a natural number that is the product of exactly two prime numbers. These two primes can be the same (e.g., 9 = 3 * 3).
Here's the Python code implementation:pythondef isPrime(num): 'Checks if a number is prime.' if num < 2: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True
def isSemiprime(n): 'Checks if a number is semiprime.' prime_count = 0 for i in range(2, int(n**0.5) + 1): if n % i == 0: if isPrime(i) and isPrime(n // i): prime_count += 1 return prime_count == 2
Test casesassert isSemiprime(6) == Trueassert isSemiprime(9) == Trueassert isSemiprime(1) == Falseassert isSemiprime(7) == Falseassert isSemiprime(12) == False
Explanation:
-
isPrime(num)Function: - Takes an integernumas input. - ReturnsTrueifnumis prime,Falseotherwise. - A prime number is greater than 1 and only divisible by 1 and itself. - The function iterates from 2 up to the square root ofnum. If any number in this range dividesnumevenly, thennumis not prime. -
isSemiprime(n)Function: - Takes an integernas input. - ReturnsTrueifnis semiprime,Falseotherwise. - It iterates from 2 to the square root ofn. - For each divisori, it checks if bothiandn//iare prime numbers using theisPrimefunction. - If exactly two prime factors are found, the number is semiprime.
How the Code Works:
- The
isSemiprimefunction efficiently checks for semiprimes by iterating only up to the square root of the input number. - If a divisoriis found, it also checks its corresponding factorn//ifor primality. - Theprime_countvariable keeps track of the number of prime factors found.
This implementation provides a clear and efficient way to determine if a number is semiprime in Python.
原文地址: https://www.cveoy.top/t/topic/SKY 著作权归作者所有。请勿转载和采集!