Advertisement
veselka_a

MultiplicationUsing BitwiseOperations

Nov 24th, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2.  
  3. namespace MultiplyIntegersBitwise
  4. {
  5.     class MultiplyTwoIntegersBitwiseOpeartion
  6.     {
  7.         static void Main()
  8.         {
  9.             // Multiply integers using bitwise operators.
  10.            
  11.             // http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication
  12.          
  13.  
  14.  
  15.             Console.WriteLine("Please enter first number n1 = ");
  16.             int n1 = Int32.Parse(Console.ReadLine());
  17.             Console.WriteLine("Please enter second number n2 = ");
  18.             int n2 = Int32.Parse(Console.ReadLine());
  19.             int product=0;
  20.  
  21.             if (n1 % 2 != 0)
  22.             {
  23.                 product = n2;
  24.             }
  25.                 do
  26.                 {
  27.                     n1 = (n1 >> 1);
  28.                     n2 = (n2 << 1);
  29.  
  30.                     if (n1 % 2 != 0)
  31.                     {
  32.                         product = n2 + product;
  33.                     }
  34.                 }
  35.  
  36.                 while (n1 >= 1);
  37.                 Console.WriteLine(product);
  38.          
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement