Problem Description:
The program takes in a number and checks if it is a prime number.
Problem Solution:
1. Take in the number to be checked and store it in a variable.
2. Initialize the count variable to 0.
3. Let the for loop range from 2 to half of the number (excluding 1 and the number itself).
4. Then find the number of divisors using the if statement and increment the count variable each time.
5. If the number of divisors is lesser than or equal to 0, the number is prime.
6. Print the final result.
5. Exit.
Python Program/Source Code:
class prime:
def __init__(self,n):
self.n=n
def isPrime(self):
k=0
for i in range(2,self.n//2+1):
if(self.n%i==0):
k=k+1
if k==0 and self.n!=1:
print("Number is prime")
else:
print("Number isn't prime")
def main():
a=int(input("Enter number: "))
num1=prime(a)
num1.isPrime()
if __name__ == "__main__":
main()
Program Explanation:
1. User must enter the number to be checked and store it in a different variable.
2. The count variable is first initialized to 0.
3. The for loop ranges from 2 to the half of the number so 1 and the number itself aren%u2019t counted as divisors.
4. The if statement then checks for the divisors of the number if the remainder is equal to 0.
5. The count variable counts the number of divisors and if the count is lesser or equal to 0, the number is a prime number.
6. If the count is greater than 0, the number isn%u2019t prime.
7. The final result is printed.
Runtime Test Cases:
Case 1:
Enter number: 7
Number is prime
Case 2:
Enter number: 35
Number isn't prime
Comments