欧拉计划42题

/**
* 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值