python判断素数程序_使用面向对象方法检查素数的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)

# 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判断素数程序

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值