Pages

Showing posts with label factorials. Show all posts
Showing posts with label factorials. Show all posts

Sunday, September 13, 2009

Euler Problem 48 solution

Time (s): ~0.034
package margusmartseppcode.From_40_to_49;

public class Problem_48 {
 public static void main(String[] args) {
  long result = 0, d10 = 10000000000L;
  for (long u = 1, tmp = u; u <= 1000; result += tmp, ++u, tmp = u)
   for (long v = 1; v < u; ++v)
    tmp = (tmp * u) % d10;

  System.out.println(result % d10);
 }
}
Time (s): ~0.224
package margusmartseppcode.From_40_to_49;

import java.math.BigInteger;

public class Problem_48 {
 // Note: i = 2 !!!
 public static void main(String[] args) {
  BigInteger num = BigInteger.ONE;
  for (int i = 2; i < 1000; i++)
   num = num.add(BigInteger.valueOf(i).pow(i));
  String result = num.toString();
  System.out.println(result.substring(result.length() - 10));
 }
}

Tuesday, September 8, 2009

Euler Problem 20 solution

Time (s): ~0.001
package margusmartseppcode.From_20_to_29;

import java.math.BigInteger;

public class Problem_20 {
 static final int maxSize = 101;
 static BigInteger f[] = new BigInteger[maxSize];
 static {
  f[0] = BigInteger.ONE;
  for (int i = 1; i < maxSize; i++)
   f[i] = f[i - 1].multiply(BigInteger.valueOf(i));
 }

 public static void main(String[] args) {
  int sum = 0;

  for (char c : f[100].toString().toCharArray())
   sum += Character.getNumericValue(c);

  System.out.println(sum);
 }
}

Euler Problem 15 solution

Time (s): ~0.001
package margusmartseppcode.From_10_to_19;

import java.math.BigInteger;

public class Problem_15 {
 static final int maxSize = 42;
 static BigInteger f[] = new BigInteger[maxSize];
 static {
  f[0] = BigInteger.ONE;
  for (int i = 1; i < maxSize; i++)
   f[i] = f[i - 1].multiply(BigInteger.valueOf(i));
 }

 public static void main(String[] args) {
  // s=x=y
  // !(x+y)/!x*!y
  int s = 20;
  System.out.println(f[s + s].divide((f[s].multiply(f[s]))));
 }
}