Created
February 12, 2012 21:54
-
-
Save vj--/1811033 to your computer and use it in GitHub Desktop.
one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vijayraj.learn; | |
import java.math.BigInteger; | |
import java.util.ArrayList; | |
public class Problem1 { | |
public static void main(String args[]) | |
{ | |
//check if the sum is equal to the value | |
int i = 1; | |
while(true){ | |
int output = R(i); | |
if(output==Integer.parseInt(args[0]) || output==0) | |
{ | |
System.out.println("The answer is : " + i); | |
break; | |
} | |
i++; | |
} | |
} | |
public static int R(int n) | |
{ | |
BigInteger factorial = Factorial4.factorial(n); | |
int sum = sum(factorial.toString()); | |
System.out.println(n + " - " + factorial.toString() + " - " + sum); | |
return sum; | |
} | |
public static int sum(String factorialString) | |
{ | |
int length=factorialString.length(); | |
int sum = 0; | |
for(int i=length-1; i>=0; i--) | |
{ | |
sum+=(Character.getNumericValue(factorialString.charAt(i))); | |
} | |
return sum; | |
} | |
} | |
/** | |
* This version of the program uses arbitrary precision integers, so it | |
* does not have an upper-bound on the values it can compute. It uses an | |
* ArrayList object to cache computed values instead of a fixed-size | |
* array. An ArrayList is like an array, but can grow to any size. The | |
* factorial() method is declared "synchronized" so that it can be safely | |
* used in multi-threaded programs. Look up java.math.BigInteger and | |
* java.util.ArrayList while studying this class. | |
* Prior to Java 1.2, use Vector instead of ArrayList | |
*/ | |
class Factorial4 { | |
protected static ArrayList<BigInteger> table = new ArrayList<BigInteger>(); // create cache | |
static | |
{ // Initialize the first element of the cache with !0 = 1. | |
table.add(BigInteger.valueOf(1)); | |
} | |
/** The factorial() method, using BigIntegers cached in a ArrayList */ | |
public static synchronized BigInteger factorial(int x) { | |
if (x < 0) | |
throw new IllegalArgumentException("x must be non-negative."); | |
for (int size = table.size(); size <= x; size++) { | |
BigInteger lastfact = (BigInteger) table.get(size - 1); | |
BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size)); | |
table.add(nextfact); | |
} | |
return (BigInteger) table.get(x); | |
} | |
/** | |
* A simple main() method that we can use as a standalone test | |
* program for our factorial() method. | |
*/ | |
public static void main(String[] args) { | |
for (int i = 0; i <= 50; i++) | |
System.out.println(i + "! = " + factorial(i)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment