赞
踩
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,
下面是该程序的实现,
- # 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判断素数程序
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。