Showing posts with label prime factorization. Show all posts
Showing posts with label prime factorization. Show all posts

Saturday, September 12, 2009

Euler Problem 6

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Powershell Solution:

  1. $SumOfSq = 1..100|%{[Math]::pow($_,2)}|measure -sum|%{$_.sum} 
  2. $SqOfSum = 1..100|measure -sum|%{[Math]::pow($_.sum,2)} 
  3. echo ($SqOfSum - $SumOfSq

Note: The solution may not be the optimized one… just a quick hack… I’ll revisit later for optimization if time permits… :-)

Friday, September 11, 2009

Euler Problem 5

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 number that is evenly divisible by all of the numbers from 1 to 20?

Powershell Solution:

This can be done manually (pen/paper) using prime factorization.
However, since I love powershell… We’ll use it with prime factorization in mind…

  1. function Get-Factors($number
  2.     [Array]$result = {1} 
  3.     $factor = 2 
  4.     while($number -gt 1) 
  5.     { 
  6.         if($number%$factor -eq 0) 
  7.         { 
  8.             $result += $factor 
  9.             $number /= $factor 
  10.         }  
  11.         else 
  12.         { 
  13.             $factor += 1 
  14.         } 
  15.     }  
  16.      
  17.     return $result 
  18.  
  19. function Get-NextMultiple($currentMultiple, $currentFactor
  20.     foreach($factor in Get-Factors($currentFactor)) 
  21.     { 
  22.         $currentMultiple = $currentMultiple * $factor.ToString() 
  23.         if($currentMultiple%$currentFactor -eq 0) 
  24.         { 
  25.             return $currentMultiple 
  26.         } 
  27.     } 
  28.  
  29. $currentMultiple = 1 
  30. 1..20|foreach{($currentMultiple = Get-NextMultiple $currentMultiple $_)}|measure -max|%{$_.Maximum} 

Note: The solution may not be the optimized one… just a quick hack… I’ll revisit later for optimization if time permits… :-)