三角形数序列中第 n 项的定义是: tn = ½n(n+1); 因此前十个三角形数是:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
通过将一个单词中每个字母在字母表中的位置值加起来,我们可以将一个单词转换为一个数。例如,单词SKY的值为19 + 11 + 25 = 55 = t10。如果单词的值是一个三角形数,我们称这个单词为三角形单词。
words.txt (右键另存为)是一个16K的文本文件,包含将近两千个常用英语单词。在这个文件中,一共有多少个三角形词?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Problem42
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
try
{
howmany();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}
static void howmany() throws IOException
{
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/XINSHANG/Desktop/words.txt"));
String temp = "";
String str = "";
while ( (temp = bf.readLine())!= null)
{
str += temp;
}
str = str.substring(1);
String arr[] = str.split("\\W+");
int answer = 0;
for (int i = 0; i < arr.length; i++)
{
char ch[] = arr[i].toCharArray();
int sum = 0;
for (int j = 0; j < ch.length; j++)
{
sum += (int)(ch[j] - 64);
}
if (istrianglenu(sum))
{
answer ++;
}
}
System.out.println(answer);
}
static boolean istrianglenu(int sum)
{
sum *= 2;
int n = (int)Math.sqrt(sum);
if (n * (n + 1) == sum)
{
return true;
}
return false;
}
}
answer: 162
time: 40