Thursday, January 10, 2013

Amicable Number

import java.util.ArrayList;

/**
 @author Umang
 */
/**
 * Let d(n) be defined as the sum of proper divisors of n 
 * (numbers less than n which divide evenly into n).
 
 * If d(a) = b and d(b) = a, where a  b, then a and b are an amicable pair 
 * and each of a and b are called amicable numbers.
 
 * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 
 * 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 
 * 71 and 142; so d(284) = 220.
 
 * Evaluate the sum of all the amicable numbers under 10000.
 */
public class Problem21
{

    private static boolean isAmicable(int no)
    {
        long sum = sum(getEvenDivisors(no));
        long no2 = sum(getEvenDivisors(sum));
        return no == no2 && sum != no;
    }

    private static long sum(ArrayList<Long> numbers)
    {
        long ans = 0;
        for (Long number : numbers)
        {
            ans += number;
        }
        return ans;
    }

    private static ArrayList<Long> getEvenDivisors(long n)
    {
        long root = Math.round(Math.sqrt(n)) 1;

        ArrayList<Long> test = new ArrayList<Long>();
        test.add(1L);
        for (long i = 2; i <= root; i++)
        {
            if (n % i == 0)
            {
                test.add(i);
                test.add(n / i);
            }
        }
        return test;
    }

    public static void main(String[] args)
    {
        long sum = 0;
        for (int i = 0; i < 10000; i++)
        {
            if (isAmicable(i))
            {
                sum = sum + i;
            }
        }
        System.out.println("Sum = " + sum);
    }
}

Circular Primes

package javaapplication3;

import java.util.ArrayList;

/**
 * The number, 197, is called a circular prime because all rotations of the
 * digits: 197, 971, and 719, are themselves prime.
 *
 * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
 * 73, 79, and 97.
 *
 * How many circular primes are there below one million?
 */
/**
 @author Umang
 */
public class Problem35
{

    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;
    }

    private static int getCount(long no)
    {
        ArrayList<Long> numbers = getDigits(no);
        return numbers.size();
    }

    public static long sumOfFactorialOfEach(ArrayList<Integer> numbers)
    {
        long sum = 0;

        for (int no : numbers)
        {
            sum += factorial(no);
        }
        return sum;
    }

    static boolean isPrime(long n)
    {
        //check if n is a multiple of 2
        if (n % == 0)
        {
            return false;
        }
        //check the odds
        for (long i = 3; i * i <= n; i += 2)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
        return true;
    }

    static String rotate(String number)
    {
        return number.subSequence(1, number.length()) "" + number.charAt(0);
    }

    private static long factorial(long no)
    {
        return no == : no * factorial(no - 1);
    }

    static boolean checkRotationsAndPrime(long no)
    {
        boolean allPrimes = true;
        String strNo = new Long(no).toString();
        int rotations = getCount(no);
        for (int i = 0; i < rotations; i++)
        {
            if (!isPrime(new Long(strNo)))
            {
                allPrimes = false;
            }
            strNo = rotate(strNo);
        }
        return allPrimes;
    }

    public static void main(String[] args)
    {
        long count = 0;
        for (int i = 1; i <= 1000000; i++)
        {
            if (checkRotationsAndPrime(i))
            {
                count++;
            }
        }
        System.out.println("\nCount is " + count);
    }
}

Problem 18

package javaapplication3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * By starting at the top of the triangle below and moving to adjacent numbers
 * on the row below, the maximum total from top to bottom is 23.
 *
 *    3
 *   7 4
 *  2 4 6
 * 8 5 9 3
 *
 * That is, 3 + 7 + 4 + 9 = 23.
 *
 * Find the maximum total from top to bottom of the triangle below:
 *
 *                        75
 *                      95 64
 *                     17 47 82
 *                   18 35 87 10
 *                 20 04 82 47 65
 *               19 01 23 75 03 34
 *              88 02 77 73 07 63 67
 *             99 65 04 28 06 16 70 92
 *           41 41 26 56 83 40 80 70 33
 *         41 48 72 33 47 32 37 16 94 29
 *        53 71 44 65 25 43 91 52 97 51 14
 *      70 11 33 28 77 73 17 78 39 68 17 57
 *    91 71 52 38 17 14 91 43 58 50 27 29 48
 *  63 66 04 68 89 53 67 30 73 16 69 87 40 31
 * 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
 *
 * NOTE: As there are only 16384 routes, it is possible to solve this problem by
 * trying every route. However, Problem 67, is the same challenge with a
 * triangle containing one-hundred rows; it cannot be solved by brute force, and
 * requires a clever method! ;o)
 */
/**
 *
 @author Umang
 */
public class Problem18
{

    /**
     * get the file content from given location
     @return file content in string format
     */
    private static String getFileContent()
    {
        StringBuilder content = new StringBuilder("");

        File aFile = new File("D:/input.txt");
        Scanner aScanner = null;
        try
        {
            aScanner = new Scanner(aFile);
        
        catch (FileNotFoundException ex)
        {
            System.out.println("File could not be readed");
            ex.printStackTrace();;
            System.exit(0);
        }
        while (aScanner.hasNextLine())
        {
            content = content.append(aScanner.nextLine() "\n");
        }
        return content.toString();
    }

    /**
     * gets the numbers in format of  LinkedList<LinkedList<Integer>>
     @return  LinkedList<LinkedList<Integer>> from the ifile
     */
    private static LinkedList<LinkedList<Integer>> getList()
    {
        LinkedList<LinkedList<Integer>> result = new LinkedList< LinkedList< Integer>>();

        String content = getFileContent();
        StringTokenizer lineTokenizer = new StringTokenizer(content, "\n\r");
        while (lineTokenizer.hasMoreTokens())
        {
            LinkedList<Integer> row = new LinkedList<Integer>();

            StringTokenizer numberTokenizer = new StringTokenizer(lineTokenizer.nextToken()" ");
            while (numberTokenizer.hasMoreTokens())
            {
                Integer no = new Integer(numberTokenizer.nextToken());
                row.add(no);
            }

            result.add(row);

        }
        return result;
    }

    /**
     
     @param rows is the LinkedList<LinkedList<Integer>> where everything is stored
     @param row_no is the row number
     @param col_no is the column number
     @return the actual number at given row and column from LinkedList<LinkedList<Integer>>
     @throws Exception if no number is found in the list (assuming that the 
     * number is never 0 in the list)
     */
    public static int get_item_at(LinkedList<LinkedList<Integer>> rows, int row_no, int col_nothrows Exception
    {
        int no = 0;

        int row_count = 0;
        int col_count = 0;

        for (LinkedList<Integer> row : rows)
        {
            col_count = 0;
            for (Integer number : row)
            {
                if (row_no == row_count && col_count == col_no)
                {
                    no = number;
                    break;
                }
                col_count++;
            }
            row_count++;
        }
        if (no == 0)
        {
            throw new Exception("No such item");
        }
        return no;
    }

    public static void main(String[] argsthrows Exception
    {
        LinkedList<LinkedList<Integer>> numbers = getList();
        System.out.println("Ans is " + getHighestSumFromList(numbers, 00));
    }

    private static int getHighestSumFromList(LinkedList<LinkedList<Integer>> rows, int row, int colthrows Exception
    {
        int currunt_no = get_item_at(rows, row, col);
        int mul_left = 0;
        int mul_right = 0;
        try
        {
            mul_left = getHighestSumFromList(rows, row + 1, col)  + currunt_no;
            mul_right = getHighestSumFromList(rows, row + 1, col + 1)  + currunt_no;
        
        catch (Exception e)
        {
            // if at the end of the list then return the currunt value 
            return get_item_at(rows, row, col);
        }
        int bigger_number =  mul_left > mul_right ? mul_left : mul_right;
        return bigger_number;

    }
}

Wednesday, January 9, 2013

Problem 92

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 == || 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);
    }
}

Tuesday, January 8, 2013

Sieve of Eratosthenes - primes


import java.util.LinkedList;
import java.util.Scanner;

/**
 * 2:42 - 3:30
 */

/**
 * http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes To find all the prime
 * numbers less than or equal to a given integer n by Eratosthenes' method: 
 * 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n). 
 * 2. Initially, let p equal 2, the first prime number. 
 * 3. Starting from p, count
 *    up in increments of p and mark each of these numbers greater than p itself 
 *    in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that 
 *    some of them may have already been marked. 
 * 4. Find the first number greater than p in
 *    the list that is not marked. If there was no such number, stop. Otherwise,
 *    let p now equal this number (which is the next prime), and 
 *    repeat from step 3.
 */
/**
 @author Umang Bhatt
 */
class Node
{

    private int no;
    private boolean marked;

    public Node(int no)
    {
        this.no = no;
        marked = false;
    }

    public int getNo()
    {
        return no;
    }

    public void setNo(int no)
    {
        this.no = no;
    }

    public boolean isMarked()
    {
        return marked;
    }

    public void setMarked(boolean marked)
    {
        this.marked = marked;
    }
}

public class SieveOfEratosthenes
{
    
    public static void main(String[] args)
    {
        Scanner aScanner = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        int no = 0;
        try
        {
            no = aScanner.nextInt();
        
        catch (java.util.InputMismatchException e)
        {
            System.out.println("You entered invalid number. Can not eontinue");
            System.exit(0);
        }

        LinkedList<Integer> primeNumberList = getAllPrimesLessThan(no);

        System.out.println("");
        for (Integer primeNo : primeNumberList)
        {
            System.out.print(primeNo + " ");
        }
    }
    
    /**
     * takes a number and returns all the primes.
     @param no is the maximum no. the primes will be below this number.
     @return  linked list of integers having only prime numbers
     */
    public static LinkedList<Integer> getAllPrimesLessThan(int no)
    {
        LinkedList<Integer> primeNumberList = new LinkedList<Integer>();
        LinkedList<Node> allNUmberList = getNodeListWithItemsLessThan(no);

        primeNumberList.addAll(getThefirstUnmarkedAndMarkOtherMultiplesIn(allNUmberList));
        primeNumberList.addAll(getUnMarkedIntegers(allNUmberList));

        return primeNumberList;
    }
    
    /**
     * This method created a list of nodes with values between 2 and given number no
     @param no is the limit
     @return the list of nodes 
     */
    private static LinkedList<Node> getNodeListWithItemsLessThan(int no)
    {
        LinkedList<Node> nodeList = new LinkedList<Node>();
        for (int i = 2; i <= no; i++)
        {
            Node aNode = new Node(i);
            nodeList.add(aNode);
        }
        return nodeList;
    }
    
    /**
     * This method adds the first node. Adds it to the primeNumber list and then
     * marks all multiples of that number as marked true
     *
     @param allNUmberList is the list of nodes created initially
     @return the list of integers.
     */
    private static LinkedList<Integer> getThefirstUnmarkedAndMarkOtherMultiplesIn(LinkedList<Node> allNUmberList)
    {
        LinkedList<Integer> primeNumberList = new LinkedList<>();
        for (Node aNode : allNUmberList)
        {
            if (aNode.isMarked() == false && hasUnmarkedNodes(allNUmberList))
            {
                    Node curruntNode = getFirstUnmarked(allNUmberList);
                    curruntNode.setMarked(true);
                    primeNumberList.add(curruntNode.getNo());
                    markMultiples(allNUmberList, curruntNode.getNo());
            }
        }
        return primeNumberList;
    }
    
    /**
     * returns the first un-marked node in the list.
     @param aNodeList is the list of nodes.
     @return the first un-marked node.
     */
    private static Node getFirstUnmarked(LinkedList<Node> aNodeList)
    {
        Node returnNode = null;
        for (Node aNode : aNodeList)
        {
            if (!aNode.isMarked())
            {
                returnNode = aNode;
                break;
            }
        }
        return returnNode;
    }
    
    /**
     * checks whether the list has unmarked nodes
     @param aNodeList
     @return boolean stating whether the list has unmarked nodes or not.
     */
    private static boolean hasUnmarkedNodes(LinkedList<Node> aNodeList)
    {
        boolean hasUnmarkedEntries = false;
        for (Node aNode : aNodeList)
        {
            if (!aNode.isMarked())
            {
                hasUnmarkedEntries = true;
                break;
            }
        }
        return hasUnmarkedEntries;
    }

    /**
     * this method marks all the numbers that are multiples of given number in 
     * the passed list of nodes.
     @param nodeList is the list of nodes constructed originally
     @param number is the number of which's multiples will be marked.
     */
    private static void markMultiples(LinkedList<Node> nodeList, int number)
    {
        for (Node aNode : nodeList)
        {
            if (aNode.getNo() % number == 0)
            {
                aNode.setMarked(true);
            }
        }
    }

    /**
     * returns all the nodes that are un-marked.
     @param allNUmberList
     @return list of un-marked nodes
     */
    private static LinkedList<Integer> getUnMarkedIntegers(LinkedList<Node> allNUmberList)
    {
        LinkedList<Integer> primeNumberList = new LinkedList<>();
        for (Node aNode : allNUmberList)
        {
            if (!aNode.isMarked())
            {
                primeNumberList.add(aNode.getNo());
            }
        }
        return primeNumberList;
    }

}