Project Euler:Problem 91 Right triangles with integer coordinates

来源:互联网 发布:红苹果预算软件 编辑:程序博客网 时间:2024/04/30 13:04

The points P (x1y1) and Q (x2y2) are plotted at integer co-ordinates and are joined to the origin, O(0,0), to form ΔOPQ.


There are exactly fourteen triangles containing a right angle that can be formed when each co-ordinate lies between 0 and 2 inclusive; that is,
0 ≤ x1y1x2y2 ≤ 2.


Given that 0 ≤ x1y1x2y2 ≤ 50, how many right triangles can be formed?


先确定P点坐标(x1,y1)   1<=x1,y1<=50

再确定与OP垂直的直线PQ

则PQ上所有整数坐标点分别与P点和O点构成了一个直角三角形且直角位于P点上


OP的斜率为k1=y1/x1    要化简约分一下 ,即分子分母同时除以gcd(x1,y1)  k1=dy/dx

PQ的斜率应该为-1/k1=-dx/dy


(1)。考虑PQ上的整数点的Y轴坐标小于P点Y轴坐标的情况:

则位于PQ上的整数点应该是相比较于P点坐标,其X坐标增加dy,Y轴坐标减少dx

则X轴方向,PQ上的整数坐标点个数应该是 (xmax-x1)/dy

Y轴方向,PQ上的整数坐标点个数应该是 y1/dx

综上,PQ上的整数坐标点个数为上面两个数的最小值


(2)。对于PQ上的整数点的Y轴大于P点Y轴坐标的情况:
那部分整数坐标点的个数与P1(y1,x1)的(1)情况是完全相同的


所以对于P和P1这两个关于y=x对称的两个点1<=x1,y1<=50

整数坐标点的个数之和为min( (xmax-x1)/dy,y1/dx)*2+min( (xmax-y1)/dx,x1/dy)*2


最后对于直角位于X轴上,位于Y轴上,位于O顶点这三种情况,个数都为2500

所以最后结果还要加上2500*3


import mathdef gcd(a,b):    if a<b:        a,b=b,a    while b!=0:        a=a-b        if a <b:            a,b=b,a    return ares=2500*3for i in range(1,51):    for j in range(1,51):        k=gcd(i,j)        tmp=min(math.floor((50-i)*k/j),math.floor(j*k/i))*2        res=res+tmpprint('res = ',res)



0 0