1. 约数问题(Python实现)
# 从input.txt文件当中读取数据
# 打开文件以读取文本
with open('input.txt', 'r') as file:
# 读取文件内容
content = file.read()
# 将文件内容拆分成行
lines = content.split('\n')
int_list = []
for item in lines:
# 使用空格分割字符串并将分割后的子字符串转换为整数
sub_items = item.split()
for sub_item in sub_items:
int_list.append(int(sub_item))
# 打印转换后的整数列表
print(int_list)
number1 = int_list[0]
number2 = int_list[1]
print("从输入文件当中读出的数据分别为:")
print(number1)
print(number2)
# 定义方法,计算某个元素的约数个数
def Calculator(x):
sum_yushu = 0
for i in range(1,x+1):
if x%i ==0:
sum_yushu= sum_yushu+1
return sum_yushu
# 定义方法,计算a,b之间约数个数最多的数x
def Maxdivisor(n1,n2):
divisorlist = []
for i in range(n1,n2+1):
dnumber = Calculator(i)
divisorlist.append(dnumber)
max_index = divisorlist.index(max(divisorlist))
max_item = n1+max_index
return max_item
# 调用以上函数,计算输入值之间约数最多的数
max_item_input = Maxdivisor(number1,number2)
print("在这两个输入的数之间,拥有约数个数最多个数的数是:")
print(max_item_input)
# 打开文件以写入文本
str_output = str(max_item_input)
with open('output.txt', 'w') as file:
# 将变量值写入文件
file.write(str_output)
print("成功写入output.txt文件当中")
输出:
2. 使用多种方法判断一个数是否为素数
import random
import time
import matplotlib.pyplot as plt
# 定义快速模运算
def quick_mod(num1, num2, num3):
result = 1
while num2 > 0:
if (num2 & 1) == 1:
result = (result * num1) % num3
num1 = (num1 * num1) % num3
num2 = num2 >> 1
return result
# 定义遍历方法,判断一个数是否为素数(该方法的正确率为100%)
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# 使用费马小定理方法判断素数(概率性)
def is_prime_fermat(n, num_tests=1):
if n <= 1:
return False
if n <= 3:
return True
for _ in range(num_tests):
a = random.randint(2, n - 2)
if quick_mod(a, n - 1, n) != 1:
return False
return True
# 定义米勒-拉宾素数测试方法
def miller_rabin_test(n, k=5):
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
# 将 n - 1 表示成 (2^r) * d 的形式
r = 0
d = n - 1
while d % 2 == 0:
r += 1
d //= 2
# 进行 k 轮测试
for _ in range(k):
a = random.randint(2, n - 2)
x = quick_mod(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = quick_mod(x, 2, n)
if x == n - 1:
break
else:
return False
return True
# 定义AKS素性测试方法
def is_prime_aks(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
r = 4
while r * r <= n:
if n % r == 0:
return False
r += 1
# 检查 a^(n-1) ≡ 1 (mod n) 对于所有 1 < a < sqrt(n)
max_a = int(n**0.5) + 1
for a in range(2, max_a):
if pow(a, n - 1, n) != 1:
return False
return True
# 初始化数据
numbers = list(range(1, 10001)) # 1到10000之间的数字
fermat_accuracy = []
miller_rabin_accuracy = []
aks_accuracy = []
brute_force_accuracy = []
fermat_timings = []
miller_rabin_timings = []
aks_timings = []
brute_force_timings = []
for n in numbers:
start_time = time.time_ns()
brute_force_result = is_prime(n)
end_time = time.time_ns()
brute_force_timings.append((end_time - start_time) // 1000) # 将纳秒转换为微秒
start_time = time.time_ns()
fermat_result = is_prime_fermat(n)
end_time = time.time_ns()
fermat_timings.append((end_time - start_time) // 1000)
start_time = time.time_ns()
miller_rabin_result = miller_rabin_test(n)
end_time = time.time_ns()
miller_rabin_timings.append((end_time - start_time) // 1000)
start_time = time.time_ns()
aks_result = is_prime_aks(n)
end_time = time.time_ns()
aks_timings.append((end_time - start_time) // 1000)
# 比较结果并添加到相应的准确率列表中
fermat_accuracy.append(1 if fermat_result == brute_force_result else 0)
miller_rabin_accuracy.append(1 if miller_rabin_result == brute_force_result else 0)
aks_accuracy.append(1 if aks_result == brute_force_result else 0)
# 绘制准确率图
plt.plot(numbers, fermat_accuracy, label="Fermat", marker="o", linestyle="-", color="b")
plt.plot(numbers, miller_rabin_accuracy, label="Miller-Rabin", marker="s", linestyle="--", color="g")
plt.plot(numbers, aks_accuracy, label="AKS", marker="^", linestyle="-.", color="r")
plt.xlabel("Number")
plt.ylabel("Accuracy")
plt.legend(loc="upper right")
plt.title("Prime Number Detection Accuracy")
# 绘制运行时间图
plt.figure()
plt.plot(numbers, fermat_timings, label="Fermat", marker="o", linestyle="-", color="b")
plt.plot(numbers, miller_rabin_timings, label="Miller-Rabin", marker="s", linestyle="--", color="g")
plt.plot(numbers, aks_timings, label="AKS", marker="^", linestyle="-.", color="r")
plt.xlabel("Number")
plt.ylabel("Time (us)")
plt.legend(loc="upper right")
plt.title("Prime Number Detection Time")
plt.show()
3. 使用递归解决全排列问题
# 使用递归方法解决全排列问题
def perm(start, end, arr):
if start == end:
print(arr)
return
for i in range(start, end):
arr[start], arr[i] = arr[i], arr[start] # 交换元素
perm(start + 1, end, arr) # 递归调用
arr[start], arr[i] = arr[i], arr[start] # 恢复原始顺序
# 示例用法
arr = [1, 2, 3]
perm(0, len(arr), arr)