Number of primes in range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given two integers A and B, print the number of prime numbers between them, inclusive.
|
A = int(input()) B = int(input()) prime_count = 0 for num in range(A, B + 1): if num > 1: is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: prime_count += 1 print(prime_count) |
- Reading Input:
A = int(input())
B = int(input())
- The
input()
function reads a line of text from the user.
- The
int()
function converts this input to an integer and stores it in the variables A
and B
.
- Initialize Prime Count:
- A variable
prime_count
is initialized to 0. This will be used to count the number of prime numbers between A and B.
- Iterating Through the Range and Checking for Primes:
|
for num in range(A, B + 1): if num > 1: is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: prime_count += 1 |
A for
loop iterates through the range from A
to B
(inclusive).
- For each number, if it is greater than 1, it checks if the number is prime by iterating through possible divisors from 2 to the square root of the number.
- If a divisor is found,
is_prime
is set to False
, and the loop breaks.
- If no divisor is found, the number is prime, and
prime_count
is incremented by 1.
- Print the Prime Count:
- Finally, the
print()
function outputs the value of prime_count
.