Python

Def

def **isprime**(candidate):
*# No primes are even except 2.*
*# ... Use modulo division to test for even numbers.*
if (candidate % 2) == 0:
if candidate == 2:
return True
else:
return False
*# Loop over numbers incrementing by 2 to the number.*
for i in range(3, candidate, 2):
*# No prime can be more than the square root.*
if (i * i) > candidate:
break;
*# See if the number is evenly divisible.*
if (candidate % i) == 0:
return False
*# The candidate is a prime unless it is 1.*
return candidate != 1
*# Test for primes in first 100 numbers.*
for test in range(0, 100):
if **isprime**(test):
print(test)
*# Test for primes in another range.*
for test in range(10000, 10100):
if **isprime**(test):
print(test)2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
10007
10009
10037
10039
10061
10067
10069
10079
10091
10093
10099

While

Memoize

Dictionary

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Dec 15, 2021 (edit link).