import mathfrom itertools import productfrom functools import reducedef find_min_n_direct(decimal_list, tolerance=0.0001, max_n=10000): """ 直接搜索法:从小到大尝试每个整数n,直到找到符合条件的最小值 参数: decimal_list: 小数列表 tolerance: 误差容忍度,相对于n的值 max_n: 搜索的最大n值 返回: 满足条件的最小整数n,如果未找到则返回None """ for n in range(1, max_n + 1): valid = True for x in decimal_list: k = round(x * n) error = abs(x * n - k) / n if error > tolerance: valid = False break if valid: return n return None# 用户输入m = int(input("请输入小数的个数 m: "))decimals = [float(input(f"请输入第 {i+1} 个小数: ")) for i in range(m)]# 执行搜索result = find_min_n_direct(decimals)# 输出结果if result: print(f"满足条件的最小整数 n = \033[1;32m{result}\033[0m") # 打印详细信息 print("\n验证结果:") for x in decimals: k = round(x * result) error = abs(x * result - k) print(f"{x} × {result} = {x*result:.4f} ≈ {k} (误差: {error:.4f})")else: print("未找到符合条件的 n。")
import matplotlib.pyplot as pltimport numpy as npdef euler_phi(n): """计算欧拉函数φ(n):小于或等于n且与n互质的正整数的个数""" result = n # 初始化为n # 检查所有可能的质因数 p = 2 while p * p <= n: if n % p == 0: # p是n的一个质因数 while n % p == 0: n //= p result -= result // p # φ(n) = φ(n) * (1 - 1/p) p += 1 # 如果n最后大于1,则n是一个质数 if n > 1: result -= result // n return result# 计算从1到1000的欧拉函数值n_values = np.arange(1, 1001)phi_values = [euler_phi(n) for n in n_values]# 创建图像plt.figure(figsize=(12, 8))plt.scatter(n_values, phi_values, s=5, alpha=0.6) # 减小点的大小,增加可读性plt.plot(n_values, phi_values, 'r-', alpha=0.2, linewidth=0.5) # 淡化连线# 添加图像标题和标签plt.title(' φ(n) (1-1000)')plt.xlabel('n')plt.ylabel('φ(n)')plt.grid(True, alpha=0.3)plt.legend(['φ(n)'], loc='upper right')# 显示图像plt.tight_layout()plt.show()