Hi, please write python code ro calculate prime numbers
- User
Hi, please write python code ro calculate prime numbers
- Assistant
Sure! Here's a Python code to calculate prime numbers:
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def get_prime_numbers(n): prime_numbers = [] for i in range(n + 1): if is_prime(i): prime_numbers.append(i) return prime_numbers # Test the code n = 50 prime_numbers = get_prime_numbers(n) print("Prime numbers up to", n, "are:", prime_numbers)In this code, the
is_prime()function checks whether a given numbernis prime or not. It iterates from 2 to the square root ofnand checks ifnis divisible by any number in that range. Ifnis divisible by any number, it returnsFalse; otherwise, it returnsTrue.The
get_prime_numbers()function generates a list of prime numbers up to a given numbern. It loops through the numbers from 0 ton, checks if each number is prime using theis_prime()function, and appends it to theprime_numberslist if it is.You can specify your desired value of
nto get the prime numbers up to that limit. In the given example, prime numbers up ton = 50are calculated and printed.