Skip to main content

Project Euler Problem 11,12,13,14,15 in Java

11) Problem 11- Project Euler Solution in Java


What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

So, I basically went through every possible way we could do the multiplication in the 20X20 grid. However, the greatest product can be found found easily if I had done multiplication diagonally rather than attempt all the trials.  But, anyway it was a good practice with 2-D arrays.

public static void main(String[] args) throws IOException {
        FileReader ff = new FileReader("Grid File (20X20).txt");
        Scanner in = new Scanner(ff);
        int[][] num = new int[20][20];
        ArrayList<Integer> list = new ArrayList();
        //reading the numbers into 2D array
        for(int i=0;i<20;i++){
            for(int j=0;j<20;j++){
                num[i][j] = in.nextInt();
            }
          }
        // Multiplying numbers vertically in downward direction
        for(int col=0;col<20;col++){
            for(int k=0;k<17;k++){
                for(int j=k;j<k+4;j++){
                    product*=num[j][col];
                }
                if(product!=0){
                    list.add(product);   
                }
                product=1;
            }
        }
        //multiplying numbers in horizontal direction
        for(int row=0;row<20;row++){
            for(int k=0;k<17;k++){
                for(int j=k;j<k+4;j++){
                    product*=num[row][j];
                }
                if(product!=0){
                    list.add(product);   
                }
                product=1;
            }
        }
        //multiplying number diagonally
        for(int j =0;j<17;j++){
            int row=j;
            for(int i=0;i<17;i++){
                for(int col =i;col<i+4;col++){
                    product*=num[row][col];
                    row++;
                }
                row=j;
                if(product!=0){
                    list.add(product);   
                }
                product=1;
            }
        }
        //multiplying diagonally in reverse order
        for(int j =0;j<17;j++){
            int row=j;
            for(int i=19;i>=3;i--){
                for(int col =i;col>i-4;col--){
                    product*=num[row][col];
                    row++;
                }
                row=j;
                if(product!=0){
                    list.add(product);   

                }
                product=1;
            }

        }
        System.out.println(Collections.max(list));
    }

 

12) Problem 12- Project Euler Solution in Java

Let us list the factors of the first seven triangle numbers:
 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?

On my first attempt, I did (triangle number/2) as number higher than that are obviously not divisible. Which didn't work; thus, I try taking square root.From the example, we can clearly see that we don't have to check all the number below the triangle number so taking the square root of a number and multiplying it by 2 gives the desired result and makes the algorithm much more faster.  For example : let's take square root of 28, it is 5.29 or 5. Now, divide by number starting with 1 to 5 to the triangle number. The only number divisible is 1,2,4 and now times it by 2 you get 6.

public static void main(String[] args) {

        boolean found = false;
        int num=0,temp=0;
        while(found==false){
            temp++;
            num+=temp;
            if(divisior(num)>500){
                found=true;
                System.out.println(num);
            }
        }
    }
    public static int divisior(int num){
        int counter=0;
        for(int i=1;i<=Math.sqrt(num);i++){
            if(num%i==0){
                counter++;
            }
        }
        return 2*counter;
    }

13) Problem 13- Project Euler Solution in Java

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

Addition Yup!! I liked this problem, it was interesting adding that many numbers and not getting right answer if you don't reverse it. Well, I did this problem two ways. The first attempt was me trying to get the answer and the second one was using Java package BigInteger. I try do it with what I knew so far in Java, but after looking at the posts in Project Euler I realized it could be done easily using Java package BigInteger.

First attempt:

FileReader ff = new FileReader("Largesum.txt");
        BufferedReader reads = new BufferedReader(ff);
        for(int i= 0; i<100;i++){
            readnum[i] = reads.readLine();
            System.out.println(readnum[i]);
        }
        for(int col=0 ;col<100;col++){
            for(int row=0 ;row<50;row++){
                num[row][col] = Character.getNumericValue(readnum[col].charAt(row));
            }
        }
       
        for( i=0 ;i<50;i++){
            for( j=0 ;j<100;j++){
                temp+= num[i][j];
            }
   
        sum[i]=temp;
        temp=0;
        }
        temp=0;
        for(i=49;i>=0;i--){
            sum[i]+=left;
            temp=sum[i]%10;
            list.add(temp);
            left=sum[i]/10;
        }
        list.add(left);
        Collections.reverse(list);
        System.out.println(list);
       
    }

Second attempt: 

File file = new File("Largesum.txt");
        FileImageInputStream r=new FileImageInputStream(file);
        BigInteger big=new BigInteger("0");
        String temp;
        while((temp=r.readLine())!=null){
        BigInteger b=new BigInteger(temp);
        big=b.add(big);
        }
        System.out.println (big.toString().substring(0, 10));

14) Problem 14- Project Euler Solution in Java

 

The following iterative sequence is defined for the set of positive integers:
nn/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?

I found this problem very interesting. The question is straight forward just need to divide a number by 2 if it's even else (3*n+1) and than repeat it until reach 1.

    int large=0,num=0;
        for(int i=2;i<=1000000;i++){
            long n=i;
            int count=1;
            while(n>1){
                if(n%2==0){
                    n=n/2;
                }
                else{
                    n=(3*n)+1;
                }
                count++;
            }
            if(count>large){
                large=count;
                num=i;
            }
        }
        System.out.println("Largest sequence num :"+num);
        System.out.println("ongest sequence value:"+large);

 

15) Problem 15- Project Euler Solution in Java

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?

 This problem can be solved without any kind of coding by using combination formula  40!/((40-20)!*20!).

public class paths {

    public static void main(String[] args) {
        BigInteger big = new BigInteger("1");
        BigInteger big2 = new BigInteger("1");
        int n=1;
        while(n<41){
            big = big.multiply(BigInteger.valueOf(n));
            //for 20!
            if(n<21){
                big2 =big2.multiply(BigInteger.valueOf(n));
            }
            n++;
        }
        System.out.println(big.divide((big2.multiply(big2))));

    }

}

Comments

Popular posts from this blog

Non-decreasing Array - LeetCode

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array.   Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000]. Source: LeetCode At first glance, it looks like an easy and straightforward problem, but believe me it's greedy problem. In the problem, you are allowed to make atmost "one" modification to make a non-decreasing array. Nondecreasing means that every element is greater than or equal to the one before it e.g. [1,3,4,4,5,6,9]. For example, [2,2,3,2,4] can this become non-decreasing? Yes, by replacing 3 with 2 =>[2,2,2,2,4]. What about this:

RLE Encoding and Decoding in C++

Given an input string, write a regular recursive function that returns the decoded (uncompresseed form) Run Length Encoded   (is a simple form of data compression where repeated character are replaced by count followed by the character repeated) string for the input string. Below are some examples: decode("*") =>* decode("3+") =>+++ decode("11*") =>*********** decode("101+") =>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ decode("abcde10+10*10+10x") =>abcde++++++++++**********++++++++++xxxxxxxxxx decode("\\") =>\ decode("\1\2\3") =>123 decode("13\7x") =>7777777777777x decode("5\\") =>\\\\\ decode("4\12\23\3") =>111122333 decode("4\\2\3") =>\\\\33 NOTE: To represent a single backslash, it’s necessary to place double backslashes (\\) in the input string to obtain the desired in

Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7    Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7   Note: The merging process must start from the root nodes of both trees.  Source: LeetCode Solution: We traverse both trees in a preorder fashion. In