Python determines whether a number is prime

Source: Internet
Author: User

To judge whether a number is prime, there are many ways, almost every language has an algorithm for judging whether it is prime, and today I share with you how Python determines whether a number is prime: 

The first thing to understand is the prime number, which is a positive integer greater than 1 that can only be divisible by itself and 1. The special note here is the number greater than 1, because 1 is not prime.

The code is as follows:

#从控制台输入一个数, determine if the prime
num0=eval (Input (' Enter a number: '))
if num0<=1:
    print (' This is not prime numbers ')
elif num0==2:
    Print (' This is a prime number! ')
else:
    i=2 while
    I<NUM0:
        if num0%i==0:
            print (' This is not a prime number ') Break
        i=i+1
    Else:
        Print (' This is a prime number! ')

Code interpretation:

The first is to get a number that is entered from the console and then determine if the number is less than or equal to 1, and if it is less than or equal to 1, then the number is not prime.

If the number is 2, then the number is prime, and the next step is to determine whether a number greater than 2 is prime.

First you loop through each number greater than 2, and then divide the numbers by the number of digits that you enter, and the range of numbers that you iterate over (2,NUM0), including 2, but excluding NUM0.

If the input number is divisible by any number in that range, then he does not satisfy the prime number, then the figure is not prime.

Python is a computer language with a very brief introduction to code. Using the Python language to accomplish a function can save programmers a lot of coding time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.