Advertisement
mrAnderson33

быстрое возведение в степень по модулю(3.A)

Jun 14th, 2018
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Быстрое_возведение_в_степень
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             int first = 0;
  15.  
  16.             var startTime = Stopwatch.StartNew();
  17.  
  18.             first = pow(1000, 1000000,999);
  19.  
  20.             startTime.Stop();
  21.  
  22.             var executingTime = startTime.Elapsed;
  23.  
  24.             Console.WriteLine($"обычное возведение в степень {executingTime}");
  25.  
  26.             Console.WriteLine(first);
  27.  
  28.             int second = 0;
  29.  
  30.            var startTime1 = Stopwatch.StartNew();
  31.  
  32.             second = fastPow(1000, 1000000,999);
  33.  
  34.             startTime1.Stop();
  35.  
  36.             var executingTime1 = startTime1.Elapsed;
  37.  
  38.             Console.WriteLine(second);
  39.  
  40.             Console.WriteLine($"быстрое возведение в степень {executingTime1}");
  41.         }
  42.  
  43.         static int pow(int num, int pow, int mod)
  44.         {
  45.             int res =1;
  46.             while (pow-- > 0) res = (res* num) % mod;
  47.             return res;
  48.         }
  49.  
  50.         static int fastPow(int num  ,int pow, int mod)
  51.         {
  52.             int res = 1;
  53.             while(pow > 0)
  54.             {
  55.                 if (pow % 2 == 1) res =(res* num) % mod;
  56.                 num = (num * num)%mod;
  57.                 pow >>= 1;
  58.             }
  59.  
  60.             return res;
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement