问题
求1-100可以构成勾股数的数。 勾股定理:a²+b²=c²
算法思想
使用遍历穷举的方法。
需要注意的是为了避免出现5 12 13和12 5 13这种情况,遍历第二个输的时候要比第一个数大。
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 求勾股数
{
class Program
{
static void Main(string[] args)
{
//求0到100的勾股数 a² + b² =c² a b c的形式输出
Console.WriteLine("a b c");
for (int i = 1; i <= 100; i++)
{
for (int j = i; j <= 100; j++)
{
for (int m = 1; m <= 100; m++)
{
if ((i*i) + (j*j ) == m*m)
{
Console.Write(i + " ");
Console.Write(j + " ");
Console.Write(m + " ");
Console.WriteLine();
}
}
}
//Console.WriteLine();
}
Console.ReadKey();
}
}
}
运行结果