package javaapplication3;
import java.util.ArrayList;
/**
* A number chain is created by continuously adding the square of the digits
* in a number to form a new number until it has been seen before.
*
* For example,
* 44 -> 32 -> 13 -> 10 -> 1 -> 1
* 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89
*
* Therefore any chain that arrives at 1 or 89 will become stuck in an
* endless loop. What is most amazing is that EVERY starting number will
* eventually arrive at 1 or 89.
*
* How many starting numbers below ten million will arrive at 89?
*/
/**
* @author Umang
*/
public class Problem92
{
public static ArrayList<Long> getDigits(long no)
{
ArrayList<Long> numbers = new ArrayList<Long>();
long temp = no;
while (temp > 0)
{
numbers.add(temp % 10);
temp /= 10;
}
return numbers;
}
public static long sumSquaresOfNo(long no)
{
ArrayList<Long> numbers = getDigits(no);
long sum = 0;
for (long curunt_no : numbers)
{
sum += (curunt_no * curunt_no);
}
return sum;
}
static boolean doesArrivesAt89(long no)
{
boolean return_val = false;
long squares = sumSquaresOfNo(no);
if (squares == 1 || squares == 89)
{
if (squares == 1)
{
return_val = false;
}
else if (squares == 89)
{
return_val = true;
}
} else
{
return_val = doesArrivesAt89(squares);
}
return return_val;
}
public static void main(String[] args)
{
int count = 0;
for (long l = 1; l <= 10000000; l++)
{
if (doesArrivesAt89(l))
{
count++;
}
}
System.out.println("count is " + count);
}
}
|
No comments:
Post a Comment