Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

Russian Peasant Multiplication

Small PowerShell exercise taken from the Programming Praxis: Russian Peasant Multiplication contest of WTF (Worse than Failure) implementing the Russian Peasant Multiplication method (for more info see original contest post)

function Invoke-RussianMultiply ([int]$a,[int]$b)
{
  "$a x $b"
  $r = 0
   while($a -ne 1){
     $a = $a/2
     $b = $b*2
     "$a x $b"
     if ($a%2) {$r+=$b;"`t+$b"}
   }
  "result : $r"
}
 

The result looks like this :

PS C:\> Invoke-RussianMultiply 18 23                                                                                    
18 x 23                                                                                                                 
9 x 46                                                                                                                  
        +46                                                                                                             
4 x 92                                                                                                                  
2 x 184                                                                                                                 
1 x 368                                                                                                                 
        +368                                                                                                            
result : 414                                                                                                            

 

Enjoy,

Greetings /\/\o\/\/

Published Thursday, July 23, 2009 10:54 AM by MoW
Filed under:

Comments

# re: Russian Peasant Multiplication

Hi MoW,

There's one problem with the solution - if the 1st number is odd the solution is wrong. I've spent a little time looking at it and think this is a suitable solution for the problem:

function Invoke-RussianMultiply ([int]$a,[int]$b)

{

 $r = 0

 do {

    "$a x $b"

    if (($a%2) -and ($a -gt 0)) {$r+=$b;"`t+$b";$a--}

    $a = $a/2

    $b = $b*2

  } until ($a -eq 0)

 "result : $r"

}

Monday, August 10, 2009 8:08 AM by cjoprey

# re: Russian Peasant Multiplication

@ cjoprey,

Oops your right a WTF ;-)

I missed that while testing

Thanks for correcting me.

Greetings MOW

Wednesday, August 12, 2009 4:53 AM by MoW
Anonymous comments are disabled