Advertisement
dimipan80

CalculateIntegerByPowerSbyte_X^Y

Apr 9th, 2014
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 KB | None | 0 0
  1. using System;
  2. using System.Globalization;
  3. using System.Threading;
  4.  
  5. class CalculateIntegerByPowerSbyte
  6. {
  7.     static void Main()
  8.     {
  9.         Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  10.         checked
  11.         {
  12.             int numX = int.Parse(Console.ReadLine());
  13.             sbyte powY = sbyte.Parse(Console.ReadLine());
  14.             decimal result = CalculateIntegerXByPowerY(numX, powY);
  15.             Console.WriteLine(result);
  16.         }
  17.     }
  18.  
  19.     static decimal CalculateIntegerXByPowerY(int numX, sbyte powY)
  20.     {
  21.         /* This method calculated result from integer X by power sbyte Y: (X^Y).
  22.          * He is the best for non-bigger integers for numX and
  23.          * very small whole numbers for power Y.
  24.          * If you must use bigger numbers, you need modify it.
  25.          * Modify return variable (result) type to double or BigInteger,
  26.          * or use System.Math.Pow(numX, powY), wich is too slower! */
  27.  
  28.         checked
  29.         {
  30.             decimal result = 0;
  31.             if (numX != 0)
  32.             {
  33.                 result = 1;
  34.                 if (powY > 0)
  35.                 {
  36.                     for (int pow = 0; pow < powY; pow++)
  37.                     {
  38.                         result *= numX;
  39.                     }
  40.                 }
  41.                 else if (powY < 0)
  42.                 {
  43.                     powY = Math.Abs(powY);
  44.                     for (int pow = 0; pow < powY; pow++)
  45.                     {
  46.                         result *= numX;
  47.                     }
  48.  
  49.                     result = 1.0m / result;
  50.                 }
  51.             }      
  52.             return result;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement