//勾股数求解
//勾股数是指3个正整数a,b,c,满足a^2+b^2=c^2。
//例如:(3,4,5),(5,12,13)
//计算100以内的勾股数
#include <stdio.h>
#define N2(x) (x)*(x)
int table[]={
N2(0),N2(1),N2(2),N2(3),N2(4),N2(5),N2(6),N2(7),N2(8),N2(9),
N2(10),N2(11),N2(12),N2(13),N2(14),N2(15),N2(16),N2(17),N2(18),N2(19),
N2(20),N2(21),N2(22),N2(23),N2(24),N2(25),N2(26),N2(27),N2(28),N2(29),
N2(30),N2(31),N2(32),N2(33),N2(34),N2(35),N2(36),N2(37),N2(38),N2(39),
N2(40),N2(41),N2(42),N2(43),N2(44),N2(45),N2(46),N2(47),N2(48),N2(49),
N2(50),N2(51),N2(52),N2(53),N2(54),N2(55),N2(56),N2(57),N2(58),N2(59),
N2(60),N2(61),N2(62),N2(63),N2(64),N2(65),N2(66),N2(67),N2(68),N2(69),
N2(70),N2(71),N2(72),N2(73),N2(74),N2(75),N2(76),N2(77),N2(78),N2(79),
N2(80),N2(81),N2(82),N2(83),N2(84),N2(85),N2(86),N2(87),N2(88),N2(89),
N2(90),N2(91),N2(92),N2(93),N2(94),N2(95),N2(96),N2(97),N2(98),N2(99),
};
//查表优化,不用乘除、平方、开方等
void test3()
{ int count=0;//结果计数
int a,b,c;
int t;
for(a=1;a<100;++a)
{ for(b=a+1;b<100;++b)
{ t=table[a]+table[b];
for(c=b+1;c<a+b;++c)
{ if(t==table[c])
{ printf("count=%d:a=%d,b=%d,c=%d/n",++count,a,b,c);
break;
}
}
}
}
}
#include <math.h>
void test2()
{ int count=0;//结果计数
int a,b,c;
int t;
for(a=1;a<100;++a)
{ for(b=a+1;b<100;++b)
{ t=a*a+b*b;
c=(int)sqrt(t);
if(c<100 && t==c*c)
{ printf("count=%d:a=%d,b=%d,c=%d/n",++count,a,b,c);
}
}
}
}
#include <windows.h>
void test()
{ long t1,t2;
printf("/ntest3:/n");
t1=GetTickCount();
test3();
t2=GetTickCount();
printf("/nuse time:%d/n",t2-t1);
printf("/ntest2:/n");
t1=GetTickCount();
test2();
t2=GetTickCount();
printf("/nuse time:%d/n",t2-t1);
}
int main()
{ test();
return 0;
}