/**
* Coded triangle numbers
* Problem 42
*
* The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
* so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
* ...
*
* By converting each letter in a word to a number corresponding to its
* alphabetical position and adding these values we form a word value. For
* example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value
* is a triangle number then we shall call the word a triangle word.
*
* Using 42.txt, a 16K text file containing nearly two-thousand common English
* words, how many are triangle words
*
*/
计算文件中,文本值能构成三角数的单词的个数
文本值:每个字母的位置和
三角数:满足n*(n-1)/2的数
分析:
计算文件中每个单词的文本值,并判断能否构成三角数
计算文本值:使用ascii码,A=65,因为文件中的字母都是大写,所以减去64就行
判断是否是三角数:
先将输入*2,开根号向上取整得到数a,判断a*(a-1)与两倍的输入是否相等
代码实现:
private static boolean isTriangle(int wordValue) {
if (wordValue == 1){
return true;
}
int temp = wordValue * 2;
int sqrt = (int) Math.floor(Math.sqrt(temp));
return (sqrt * (sqrt + 1)) == temp;
}
private static int getWordsValue(String string) {
int value = 0;
for (int i = 0; i < string.length(); i++){
value += string.getBytes()[i] - 64;
}
return value;
}
结果:162
* Coded triangle numbers
* Problem 42
*
* The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
* so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
* ...
*
* By converting each letter in a word to a number corresponding to its
* alphabetical position and adding these values we form a word value. For
* example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value
* is a triangle number then we shall call the word a triangle word.
*
* Using 42.txt, a 16K text file containing nearly two-thousand common English
* words, how many are triangle words
*
*/
计算文件中,文本值能构成三角数的单词的个数
文本值:每个字母的位置和
三角数:满足n*(n-1)/2的数
分析:
计算文件中每个单词的文本值,并判断能否构成三角数
计算文本值:使用ascii码,A=65,因为文件中的字母都是大写,所以减去64就行
判断是否是三角数:
先将输入*2,开根号向上取整得到数a,判断a*(a-1)与两倍的输入是否相等
代码实现:
private static boolean isTriangle(int wordValue) {
if (wordValue == 1){
return true;
}
int temp = wordValue * 2;
int sqrt = (int) Math.floor(Math.sqrt(temp));
return (sqrt * (sqrt + 1)) == temp;
}
private static int getWordsValue(String string) {
int value = 0;
for (int i = 0; i < string.length(); i++){
value += string.getBytes()[i] - 64;
}
return value;
}
结果:162