プログラム!
http://projecteuler.net/index.php
頭が悪いから簡単なやつだけ解いてみる。1問目は解いたので、次は20問目。
n! means n × (n - 1) × ... × 3 × 2 × 1
Find the sum of the digits in the number 100!
階乗はやっぱり再帰を使うのがかっこいいよね。
import java.math.BigInteger; public class Euler { public static void main(String[] args) { String str = factorial(BigInteger.valueOf(100)).toString(); int n = 0; for (int i = 0; i < str.length(); i++) { // n += Integer.parseInt(String.valueOf(str.charAt(i))); こっちもOK n += Character.getNumericValue(str.charAt(i)); } System.out.println(n); // 648 } private static BigInteger factorial(BigInteger n) { if (BigInteger.ONE.equals(n)) { return BigInteger.ONE; } return n.multiply(factorial(n.subtract(BigInteger.ONE))); } }
問題160も同じ階乗のメソッドが使いまわせると思ったけど、桁あふれしすぎるよな・・・。
For any N, let f(N) be the last five digits before the trailing zeroes in N!.
For example,9! = 362880 so f(9)=36288
10! = 3628800 so f(10)=36288
20! = 2432902008176640000 so f(20)=17664Find f(1,000,000,000,000)
うーん。どうやって解こうか・・・。
追記:思いついたけど実装する時間がないのであとにします。うまくいくかな。