通过使用GCD例程查找互质数并将失败视为异常,您可以使用相同的代码绘制大多数奇数和偶数尖星:
import sys
import turtle
from time import sleep
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def normal_star(size, color, points):
if points <= 4:
raise ValueError('Not enough points')
turtle.color(color)
for coprime in range(points // 2, 1, -1):
if gcd(points, coprime) == 1:
print("({},{})".format(points, coprime), file=sys.stderr)
start = turtle.position()
for _ in range(points):
turtle.forward(size)
turtle.left(360.0 / points * coprime)
turtle.setposition(start)
return
abnormal_star(size, color, points)
def abnormal_star(size, color, points):
print("Exception:", points, file=sys.stderr)
for points in range(5, 20):
turtle.reset()
normal_star(200, 'red', points)
sleep(5)
turtle.exitonclick()
对于5到20之间的点,这个算法只无法找到6的解决方案,您需要将其视为一个例外,即编写专门代码或告知用户这是一个无法处理的例外情况:
> python3 test.py
(5,2)
Exception: 6
(7,3)
(8,3)
(9,4)
(10,3)
(11,5)
(12,5)
(13,6)
(14,5)
(15,7)
(16,7)
(17,8)
(18,7)
(19,9)
(20,9)
>
针对参数200,'红色',10的输出示例如下:
![enter image description here](https://istack.dev59.com/KCfoe.webp)