Wednesday 4 August 2010

Get-MultiplyBigInteger.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script re-implements this MSDN Sample of  
  4.     multiplying a big integer. 
  5. .DESCRIPTION 
  6.     This script first tries and fails to multiple a pair of large integers. The 
  7.     script catches the error and then used BigInteger.Multiply to multiply  
  8.     the two big itegers. 
  9. .NOTES 
  10.     File Name  : Get-MultiplyBigInteger.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 
  13. .LINK 
  14.     This script posted to: 
  15.         http://www.pshscripts.blogspot.com 
  16.     MSDN Sample posted at: 
  17.         http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.multiply.aspx 
  18. .EXAMPLE 
  19.     PSH [C:\foo]: .Get-MultiplyBigInteger.ps1 
  20.     Too big for long, try biginteger 
  21.     12,193,263,111,263,526,900 
  22. #> 
  23. # Add System.Numerics namespace 
  24. $r=[system.Reflection.Assembly]::LoadWithPartialName("System.Numerics"
  25.  
  26. # Two big numbers 
  27. $number1 = 1234567890 
  28. $number2 = 9876543210 
  29.  
  30. # Try normal [long] then catch error and do biginteger 
  31. try 
  32.    [long] $product = $number1 * $number2 
  33. catch  
  34. "Too big for long, try biginteger" 
  35.    $product = New-Object System.Numerics.BigInteger 
  36.    $product = [System.Numerics.BigInteger]::Multiply($number1, $number2
  37.    $product.ToString("N0"
  38. }    

No comments: