Diskussion:Är det ett primtal

Från Wikiskola
Version från den 21 mars 2018 kl. 23.21 av Hakan (diskussion | bidrag)
Hoppa till navigering Hoppa till sök

A function evaluating if input integer is prime (in Python script):

def prime(input):
    for n in range(2, input):
        if input%n == 0:
            return False
    return True

Essentially, this evaluates whether integer x can be divisible by any number less than it (n = [2, 3, 4, ... , x-2, x-1]). However, there are two redundancies in this method:

1. If input is not divisible by 2, it will not be divisible to any other even number (4, 6, 8, ...).

2. It is not needed to evaluate integers above the square root of the input number. To elaborate, here is an example:

Evaluate if 127 is prime:
127 divisible by 2? No.
127 divisible by 3? No.
127 divisible by 5? No.
127 divisible by 7? No.
127 divisible by 9? No.
127 divisible by 11? No.
Therefore 127 is prime.

Från WikiBooks