正整数
import math
// (n) -> (factor)
def find_factor(n):
factor = 1
// If n = ab, 1 < a <= b < n, then 2 <= a <= floor(sqrt(n))
upper_bound = math.floor(math.sqrt(n))
for i in range(2, upper_bound + 1):
if n % i == 0:
factor = i
break
return factor
// (n) -> (result)
def is_prime(n):
result = False
if find_factor(n) == 1:
result = True
return result
print(is_prime(23))
print(is_prime(233))
print(is_prime(2333))
print(is_prime(23333))
print(is_prime(233333))
print(find_factor(233333))
// ----- Run Program -----
> python arithmetic.py
True
True
True
True
False
353
Euclid算法
// (a, b) -> (q, r)
def division_with_remainder(a, b):
// Python does not behave as the above definition, so we only consider positive integers
q = a // b
r = a % b
return (q, r)
// (a, b) -> (d, m, n)
def Euclidean_algorithm(a, b):
d = 0; m = 0; n = 0
dividend = a; divisor = b
// dividend = mi * a + ni * b
mi = 1; ni = 0
// divisor = oi * a + pi * b
oi = 0; pi = 1
while(divisor != 0):
(qi, ri) = division_with_remainder(dividend, divisor)
dividend = divisor
divisor = ri
(mi, ni, oi, pi) = (oi, pi, mi - qi * oi, ni - qi * pi)
d = dividend
m = mi
n = ni
return (d, m, n)
print(division_with_remainder(2333, 233))
print(division_with_remainder(233, 2333))
a = 233; b = 2333
(d, m, n) = Euclidean_algorithm(a, b)
print(d, m, n)
print(m * a + n * b)
// ----- Run Program -----
> python arithmetic.py
(10, 3)
(0, 233)
1 -781 78
1
素因子分解
// (n) -> (prime_factors)
def prime_factorization(n):
prime_factors = []
recursive_factor(n, prime_factors)
return prime_factors
// (n, prime_factors) -> ()
def recursive_factor(n, prime_factors):
if is_prime(n):
prime_factors.append(n)
else:
a = find_factor(n)
b = n // a
recursive_factor(a, prime_factors)
recursive_factor(b, prime_factors)
print(prime_factorization(233333))
print(prime_factorization(123456789))
// ----- Run Program -----
> python arithmetic.py
[353, 661]
[3, 3, 3607, 3803]
Eratosthenes筛法
// (n) -> (all_primes)
def Eratosthenes_sieve(n):
// Create a list from 2 to n
all_primes = list(range(2, n + 1))
p = 2
while(max(all_primes) > p):
// Remove 2p, 3p, ..., floor(n / p) * p from the list
for i in range(2, math.floor(n / p) + 1):
if i * p in all_primes:
all_primes.remove(i * p)
// Find the smallest number greater than p in the list
for i in range(len(all_primes)):
if all_primes[i] > p:
p = all_primes[i]
break
return all_primes
print(Eratosthenes_sieve(233))
n = 233
print(len(Eratosthenes_sieve(n)) / (n / math.log(n)))
n = 2333
print(len(Eratosthenes_sieve(n)) / (n / math.log(n)))
n = 23333
print(len(Eratosthenes_sieve(n)) / (n / math.log(n)))
// ----- Run Program -----
> python arithmetic.py
[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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233]
1.1931457559306897
1.146782702034888
1.1215847730217052