Chitika

Friday, October 29, 2004

7427466391

Do you guys know this popular problem, which was used by Google as the second stage test for anyone "smart enough" to solve the problem to send their resume to Google?

f(1) = 7182818284
f(2) = 8182845904
f(3) = 8747135266
f(4) = 7427466391
f(5) = __________

The sequence was part of an e (logarithmic) number, whose sum is 49.
Having to rest my brain for the past 9 years, I decided to give it a shot.
Here's what I came up within an hour...

f(1) = 7182818284
f(2) = 8182845904
f(3) = 8747135266
f(4) = 7427466391
f(5) = 5966290435
f(6) = 2952605956
f(7) = 0753907774
f(8) = 0777449920
f(9) = 3069697720
f(10) = 1252389784
f(11) = 3163688923
f(12) = 9229576351
f(13) = 4822082698
f(14) = 8879332036
f(15) = 6832823764
f(16) = 8328237646
f(17) = 8194558153
f(18) = 2509961818
f(19) = 0727386673
f(20) = 0868058257
f(21) = 0582574927
f(22) = 7492796104
f(23) = 7961048419
f(24) = 4841984443
f(25) = 3463244968
f(26) = 6848756023
f(27) = 9418491463
f(28) = 5209618369
f(29) = 6965521267

Here's my source code, if you guys want to try it out..

private static final BigDecimal ZERO =
  new BigDecimal ("0");
private static final BigDecimal ONE = new BigDecimal ("1");

public static BigDecimal factorial (BigDecimal a) {
  if (a.intValue() == 1) return a;
  else return a.multiply (factorial (a.subtract(ONE)));
}

public static BigDecimal e (
    int elementCount,
    int precision) {
  BigDecimal result = ZERO;
  for (int i=1; i<elementcount; i++)
    result = result.add (
      ONE.divide (
        factorial (new BigDecimal(String.valueOf(i))),
        precision,
        BigDecimal.ROUND_FLOOR));
  }
  return ONE.add (result);
}

public static List parseE (
    BigDecimal e,
    int elementCount,
    int elementsSum) {
  List result = null;
  String s = e.toString().substring(2);
  for (int i=0; i<s.length()-elementcount; i++)
    String sub = s.substring (i, i + elementCount);
    int count = 0;
    for (int j=0; j<elementcount; j++)
      count += sub.charAt(j) - '0';
    }
    if (count == elementsSum) {
      if (result == null) result = new ArrayList ();
      result.add (sub);
    }
  }
  return result;
}

public static void main (String[] args) {
  BigDecimal e = e (1000, 1000);
  System.out.println ("e = " + e);
  List magicNumbers = parseE (e, 10, 49);
  if (magicNumbers != null) {
    int count = 0;
    for (Iterator it = magicNumbers.iterator();
         it.hasNext();) {
      String s = (String) it.next();
      System.out.println ("f(" + (++count) + ") = " + s);
    }
  }
}

It was fun.. :D


1 comment:

  1. Great post, I enjoyed reading it.

    Adding you to favorites, Ill have to come back and read it again later.

    ReplyDelete