<MEMORY>Project Euler NO42

三角形数序列中第 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值