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:

  1. isPrime(num) Function: - Takes an integer num as input. - Returns True if num is prime, False otherwise. - A prime number is greater than 1 and only divisible by 1 and itself. - The function iterates from 2 up to the square root of num. If any number in this range divides num evenly, then num is not prime.

  2. isSemiprime(n) Function: - Takes an integer n as input. - Returns True if n is semiprime, False otherwise. - It iterates from 2 to the square root of n. - For each divisor i, it checks if both i and n//i are prime numbers using the isPrime function. - If exactly two prime factors are found, the number is semiprime.

How the Code Works:

  • The isSemiprime function efficiently checks for semiprimes by iterating only up to the square root of the input number. - If a divisor i is found, it also checks its corresponding factor n//i for primality. - The prime_count variable 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.

Python Function to Check for Semiprime Numbers

原文地址: https://www.cveoy.top/t/topic/SKY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录