Tuesday, 23 August 2016

Project Euler Problem 12: Highly divisible triangular number

Problem

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
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?

Solution

First attempt

The trick of counting the divisors is only check up to the square root of the number, and each time add 2 to the count. It didn't cross my mind the first time, and I checked up to half the number and each time add 1 to the count. It took forever....

      private static final int DIVISOR_NUMBER = 500;  
      public static void main(String[] args) {  
           int triangleNumber = 1;  
           int natualNumber = 2;  
           int divisorNumber = 1;  
           while (divisorNumber <= DIVISOR_NUMBER){  
                triangleNumber += natualNumber;  
                divisorNumber = divisorNumber(triangleNumber);  
                natualNumber++;  
           }  
           System.out.println(triangleNumber);  
      }  
      private static int divisorNumber(int number){  
           int count = 2;  
           int sqrt = (int)Math.sqrt(number);  
           for (int i=2; i<=sqrt; i++){  
                if (number % i == 0){  
                     count+=2;  
                }  
           }  
           if (sqrt * sqrt == number){  
                count--;  
           }  
           return count;  
      }  

Second attempt

This is really brilliant.

Kudos to kpsychas who came up with it. https://projecteuler.net/thread=12;page=3#5370

It is a bit difficult to understand the original post. So I have expanded it to make it more clear.



      private static final int DIVISOR_NUMBER = 500;  
      public static void main(String[] args) {  
           int k = 2;  
           int divisorNumberOdd = 0;  
           int divisorNumberEven = 0;  
           do{  
                k++;  
                divisorNumberOdd = divisorNumber(k) * divisorNumber(2*k-1);  
                divisorNumberEven = divisorNumber(k) * divisorNumber(2*k+1);  
           }while(divisorNumberOdd <= DIVISOR_NUMBER && divisorNumberEven <= DIVISOR_NUMBER);  
           if (divisorNumberOdd > DIVISOR_NUMBER){  
                System.out.println(k*(2*k-1));  
           }else{  
                System.out.println(k*(2*k+1));  
           }  
      }  
      private static int divisorNumber(int number){  
           int count = 2;  
           int sqrt = (int)Math.sqrt(number);  
           for (int i=2; i<=sqrt; i++){  
                if (number % i == 0){  
                     count+=2;  
                }  
           }  
           if (sqrt * sqrt == number){  
                count--;  
           }  
           return count;  
      }  

Project Euler Problem 11: Largest product in a grid

Problem

In the 20×20 grid below, four numbers along a diagonal line have been marked in red.

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

The product of these numbers is 26 × 63 × 78 × 14 = 1788696.

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

Solution

It is worth mentioning that the algorithm to calculate adjacent product for horizontal, vertical and diagonal direction can be consolidated.
      private static final int SIZE = 20;  
      private static final int[][] m = new int[SIZE][SIZE];  
      private static final int K = 4;  
      public static void main(String[] args) {  
           readFile();  
           int greatestProduct = 0;  
           for (int i=0; i<SIZE; i++){  
                for (int j=0; j<SIZE; j++){  
                     int rowProduct = adjacentProduct(i, j, 1, 0);  
                     int colProduct = adjacentProduct(i, j, 0, 1);  
                     int diagProductRight = adjacentProduct(i, j, 1, 1);  
                     int diagProductLeft = adjacentProduct(i,j, 1, -1);  
                     int tempGreatest = Math.max(Math.max(rowProduct, colProduct),   
                               Math.max(diagProductLeft, diagProductRight));  
                     greatestProduct = Math.max(greatestProduct, tempGreatest);  
                }  
           }  
           System.out.println(greatestProduct);  
      }  
      private static int adjacentProduct(int i, int j, int iStep, int jStep){  
           int iK = i+iStep*(K-1);  
           int jK = j+jStep*(K-1);  
           if (!withinBoundary(iK) || !withinBoundary(jK)){  
                return 0;  
           }  
           int product = 1;  
           for (int x=i,y=j,count=0; count<K; x+=iStep,y+=jStep, count++){  
                product *= m[x][y];  
           }  
           return product;  
      }  
      private static boolean withinBoundary(int i) {  
           return 0 <= i && i < SIZE;  
      }  
      private static void readFile() {  
           File file = new File("Q11.txt");  
           try {  
                Scanner sc = new Scanner(file);  
                int row = 0;  
                int col = 0;  
                while (sc.hasNextLine()) {  
                     int i = sc.nextInt();  
                     m[row][col] = i;  
                     col++;  
                     if (col == SIZE){  
                          col = 0;  
                          row++;  
                     }  
                }  
                sc.close();  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           }  
      }  

Monday, 22 August 2016

Project Euler Problem 8: Largest product in a series

Problem

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Solution

Two optimizations I made to make the program quicker are
  • Keep the previous product value, when it is not 0, divide the previous product value by the number at index-1, and multiply the result by the number at index+12. 
  • Check if the current sequence of numbers contains any 0s, if it does, move on to the next index. (I use bit operation to determine this. It's probably overkill, but I was so obsessed with the idea of 'going through the array only once') 
To explain the logic of determining whether a sequence of digits contains any 0s using bit operation, let's assume the length is sequence is 4, and here is a sample sequence 2708209487.

Firstly, we are checking 2708. Iterate from left to right, when we see a 0 we push a 1 to a queue, when we see a none 0, we push a 0 to the queue. The result is 0100 (decimal number 4).  The code to achieve this is

 if (numAt(i) == 0){   
   zeros |= 1 << j;    
 }   

When the result > 0, it means the sequence contains a 0.

The next sequence to check is 7082. We could repeat the previous step, but we don't have to. We can simply get rid of the right most digit of the previous result and left pad with new digit, in this case, 2.

Here is the relevant code.

 int result = previousZeros >> 1;   //Get rid of the right most digit
 if (numAt(index+NUMBER-1)==0){   
   result |= 1 << (NUMBER - 1);  //Left pad a 0 or 1 for the new digit 
 }  

Complete code

      private static final int NUMBER = 13;  
      private static final String STR =   
      "73167176531330624919225119674426574742355349194934"+  
      "96983520312774506326239578318016984801869478851843"+  
      "85861560789112949495459501737958331952853208805511"+  
      "12540698747158523863050715693290963295227443043557"+  
      "66896648950445244523161731856403098711121722383113"+  
      "62229893423380308135336276614282806444486645238749"+  
      "30358907296290491560440772390713810515859307960866"+  
      "70172427121883998797908792274921901699720888093776"+  
      "65727333001053367881220235421809751254540594752243"+  
      "52584907711670556013604839586446706324415722155397"+  
      "53697817977846174064955149290862569321978468622482"+  
      "83972241375657056057490261407972968652414535100474"+  
      "82166370484403199890008895243450658541227588666881"+  
      "16427171479924442928230863465674813919123162824586"+  
      "17866458359124566529476545682848912883142607690042"+  
      "24219022671055626321111109370544217506941658960408"+  
      "07198403850962455444362981230987879927244284909188"+  
      "84580156166097919133875499200524063689912560717606"+  
      "05886116467109405077541002256983155200055935729725"+  
      "71636269561882670428252483600823257530420752963450";  
      public static void main(String[] args) {  
           long previousProduct = calulateProduct(0, 0);  
           long greatestProduct = previousProduct;  
           int zeros = zeros(0);  
           for (int i=1; i<STR.length()-NUMBER; i++){  
                zeros = zeros(i, zeros);  
                if (zeros == 0){  
                     long product = calulateProduct(i, previousProduct);  
                     previousProduct = product;  
                     if (product > greatestProduct){  
                          greatestProduct = product;  
                     }       
                }else{  
                     previousProduct = 0;  
                }  
           }  
           System.out.println(greatestProduct);  
      }  
      private static long calulateProduct(int index, long previousProduct) {  
           if (previousProduct > 0){  
                return previousProduct / numAt(index-1) * numAt(index+NUMBER-1);   
           }  
           long product = 1;  
           for (int i=index; i<index+NUMBER; i++){  
                product *= (long)numAt(i);  
           }  
           return product;  
      }  
      private static int zeros(int index){  
           int zeros = 0;  
           for (int i=index, j=0; i<index+NUMBER; i++,j++){  
                if (numAt(i) == 0){  
                     zeros |= 1 << j;   
                }  
           }  
           return zeros;  
      }  
      private static int zeros(int index, int previousZeros){  
           if (previousZeros == -1){  
                return zeros(index);  
           }  
           int result = previousZeros >> 1;  
           if (numAt(index+NUMBER-1)==0){  
                result |= 1 << (NUMBER - 1);  
           }  
           return result;  
      }  
      private static long numAt(int index){  
           return Long.valueOf(STR.charAt(index)+"");  
      }  

Project Euler Problem 7: 10001st prime

Problem

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

Solution

Some optimization includes

  • Use an array to store found prime numbers to check future prime number candidate
  • Only check numbers 6k+1 and 6k-1, because we know other number can either be divided by 2 or 3.

      private static final int NUMBER = 10001;  
      private static final long[] primeNumbers = new long[NUMBER-1];  
      public static void main(String[] args) {  
           primeNumbers[0]=3L;  
           int index = 1;  
           for (int i=6; index < NUMBER - 1; i+=6){ //Because we start at 3 instead of 2  
                for (int j=-1; j <= 1; j+=2){ //Only test 6K+1 and 6k-1  
                     if (isPrimeNumber(i+j, index)){  
                          primeNumbers[index]=i+j;  
                          index++;  
                     }  
                     if (index >= NUMBER - 1){  
                          break;  
                     }  
                }  
           }       
           System.out.println(primeNumbers[index-1]);  
      }  
      private static boolean isPrimeNumber(long number, int index){  
           double sqrt = Math.sqrt(number);  
           for (int i = 0; primeNumbers[i] <= sqrt; i++){  
                if (number % primeNumbers[i] == 0){  
                     return false;  
                }  
           }  
           return true;  
      }  

Sunday, 21 August 2016

Project Euler Problem 5: Smallest multiple

Problem

 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

 What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Solution

Attempt 1: Count the occurrences of the prime factor for each number, and multiply them all.

      private static Map<Integer, Integer> primeNumberOccurrence = new HashMap<>();  
      public static void main(String[] args) {  
           for (int i=2; i<=20; i++){  
                updatePrimeNumberOccurrence(i);  
           }  
           int total = 1;  
           for (int key : primeNumberOccurrence.keySet()){  
                int occurrence = primeNumberOccurrence.get(key);  
                total *= Math.pow(key, occurrence);  
           }  
           System.out.println(total);  
      }  
      private static void updatePrimeNumberOccurrence(int number){  
           int divisor = 2;  
           int divisorCount = 0;  
           while(number > 1){  
                if(number % divisor == 0){  
                     number = number / divisor;  
                     divisorCount++;  
                }else{  
                     update(divisor, divisorCount);  
                     divisor++;  
                     divisorCount = 0;  
                }  
           }  
           update(divisor, divisorCount);  
      }  
      private static void update(int divisor, int divisorCount){  
           if (divisorCount != 0){  
                int oldCount = primeNumberOccurrence.get(divisor) != null ? primeNumberOccurrence.get(divisor) : 0;  
                if (divisorCount > oldCount){  
                     primeNumberOccurrence.put(divisor, divisorCount);  
                }  
           }  
      }  

Attempt 2: Use greatest common factor

      private static final int NUMBER = 20;  
      public static void main(String[] args) {  
           int total = NUMBER;  
           for (int i = NUMBER-1; i >= 2; i--){  
                //greatest common factor  
                total *= i / BigInteger.valueOf(total).gcd(BigInteger.valueOf(i)).intValue();  
           }  
           System.out.println(total);  
      }  

Project Euler Problem 4: Largest palindrome product

Problem

A palindromic number reads the same both ways.

The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

Solution

The efficiency of checking if a number is palindrome can certainly be improved, but I am more focused on optimization on two for loops.

  • Start from 999 backwards, and start j=i instead of 999
  • Check product > current largest palindrome first instead of checking product is palindrome first
  • break inner loop when we know the rest product cannot be larger than the current largest palindrome

      public static void main(String[] args) {  
           long largestPalindrome = 0;  
           for (int i = 999; i >= 100; i--){  
                for (int j = i; j >= 100; j--){  
                     long product = i * j;  
                     if (product > largestPalindrome){  
                          if (isPalindrome(product)){  
                               largestPalindrome = product;  
                               break;  
                          }  
                     }else{  
                          break;  
                     }  
                }  
           }  
           System.out.println(largestPalindrome);  
      }  
      private static boolean isPalindrome(long product) {  
           String s = String.valueOf(product);  
           return reverse(s).equals(s);  
      }  
      private static String reverse(String s) {  
           String r = "";  
           for (int i=s.length()-1; i>=0; i--){  
                r += s.charAt(i);  
           }  
           return r;  
      }  

Project Euler Problem 3: Largest prime factor

Problem

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143?

Solution


If the while loop condition changes to divisor < number, it will be extremely slow for number like 600851475145


      public static void main(String[] args) {            
           long number = 600851475143L;  
           long divisor = 2;  
           while((divisor * divisor) <= number){  
                if(number%divisor==0){  
                     number = number/divisor ;  
                }  
                divisor++;  
           }  
           System.out.println(number);  
      }