python判斷素數程序
This program will check whether a given number is Prime or Not, in this program we will divide the number from 2 to square root of that number, if the number is divided by any number in b/w then the number will not be a prime number.
該程序將檢查給定數字是否為質數 ,在此程序中,我們將數字從2除以該數的平方根,如果該數字除以b / w中的任何數字,則該數字將不是質數數。
We are implementing this program using the concept of classes and objects.
我們正在使用類和對象的概念來實現該程序。
Firstly we create the Class with Check name with 1 attributes ('number') and 2 methods, the methods are:
首先,我們使用Check名稱創建具有1個屬性( 'number' )和2個方法的Class,這些方法是:
Constructor Method: This is created using __init__ inbuilt keyword. The constructor method is used to initialize the attributes of the class at the time of object creation.
構造方法 :這是使用__init__內置關鍵字創建的。 構造函數方法用于在創建對象時初始化類的屬性。
Object Method: isPrime() is the object method, for creating object method we have to pass at least one parameter i.e. self keyword at the time of function creation.
對象方法 : isPrime()是對象方法,要創建對象方法,我們必須在函數創建時傳遞至少一個參數,即self關鍵字。
Secondly, we have to create an object of this class using a class name with parenthesis then we have to call its method for our output.
其次,我們必須使用帶有括號的類名來創建此類的對象,然后必須為其輸出調用其方法。
Below is the implementation of the program,
下面是該程序的實現,
Python代碼檢查給定數字是否為質數 (Python code to check whether a given number is prime or not)
# Define a class for Checking prime number
class Check :
# Constructor
def __init__(self,number) :
self.num = number
# define a method for checking number is prime or not
def isPrime(self) :
for i in range(2, int(num ** (1/2)) + 1) :
# if any number is divisible by i
# then number is not prime
# so return False
if num % i == 0 :
return False
# if number is prime then return True
return True
# Main code
if __name__ == "__main__" :
# input number
num = 11
# make an object of Check class
check_prime = Check(num)
# method calling
print(check_prime.isPrime())
num = 14
check_prime = Check(num)
print(check_prime.isPrime())
Output
輸出量
True
False
翻譯自: https://www.includehelp.com/python/program-to-check-prime-number-using-object-oriented-approach.aspx
python判斷素數程序