如果p是一个直角三角形的周长,三角形的三边长{a,b,c}都是整数。对于p = 120一共有三组解:
{20,48,52}, {24,45,51}, {30,40,50}
对于1000以下的p中,哪一个能够产生最多的解?
use strict; use warnings; my ($most,$p); $most=0; $p=12; for my $i (12..1000) { my $cout=0; for my $j (1..$i/2) { for my $k (1..$i/2) { if ($j*$j+$k*$k==($i-$j-$k)*($i-$j-$k)) { $cout++; } else { next; } } } if ($cout>$most) { $most=$cout; $p=$i; } else { next; } } print "$p\n";
三角形数序列中第 n 项的定义是: tn = ½n(n+1); 因此前十个三角形数是:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
通过将一个单词中每个字母在字母表中的位置值加起来,我们可以将一个单词转换为一个数。例如,单词SKY的值为19 + 11 + 25 = 55 = t10。如果单词的值是一个三角形数,我们称这个单词为三角形单词。
words.txt (右键另存为)是一个16K的文本文件,包含将近两千个常用英语单词。在这个文件中,一共有多少个三角形词?
use strict; use warnings; my (%hash,$sum); for my $i (1..1000) { my $number=$i*($i+1)/2; $hash{$number}="A"; } my $cout=0; my $in_in = "words.txt"; open my $in, '<', $in_in or die "cannot open\n"; while(<$in>) { chomp; my @word=split/,/,$_; foreach my $word (@word) { $sum=0; my $length=length($word); for my $j (1..($length-2)) { my $zi_mu=substr($word,$j,1); $sum=$sum+ord($zi_mu)-64; } if (exists $hash{$sum}) { $cout++; } else { next; } } } close $in; print "$cout\n";