当前位置:   article > 正文

python判断素数程序_使用面向对象方法检查素数的Python程序

check prime number python

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,这些方法是:

  1. 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__内置关键字创建的。 构造函数方法用于在创建对象时初始化类的属性。

  2. 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)

  1. # Define a class for Checking prime number
  2. class Check :
  3. # Constructor
  4. def __init__(self,number) :
  5. self.num = number
  6. # define a method for checking number is prime or not
  7. def isPrime(self) :
  8. for i in range(2, int(num ** (1/2)) + 1) :
  9. # if any number is divisible by i
  10. # then number is not prime
  11. # so return False
  12. if num % i == 0 :
  13. return False
  14. # if number is prime then return True
  15. return True
  16. # Main code
  17. if __name__ == "__main__" :
  18. # input number
  19. num = 11
  20. # make an object of Check class
  21. check_prime = Check(num)
  22. # method calling
  23. print(check_prime.isPrime())
  24. num = 14
  25. check_prime = Check(num)
  26. print(check_prime.isPrime())

Output

输出量

  1. True
  2. False

翻译自: https://www.includehelp.com/python/program-to-check-prime-number-using-object-oriented-approach.aspx

python判断素数程序

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/593350
推荐阅读
相关标签
  

闽ICP备14008679号