Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. namespace PrimalityTester
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19.  
  20. //Uses Fermats Little Thm
  21. private void solve_Click(object sender, EventArgs e)
  22. {
  23. long N = Convert.ToInt64(input.Text);
  24. long k = Convert.ToInt64(k_value.Text);
  25. Random random = new Random();
  26. for (int i = 1; i <= k && i <= (N-1); i++) //Run k tests, max N-1 since the set of numbers to test a^(N-1) must be between 1 and N-1
  27. {
  28. int random = rdm.Next(1, (int)N); //Random.Next is O(1) according to docs
  29. if (Modexp(random, N - 1, N) != 1)
  30. {
  31. output.Text = "Nope, it's not prime";
  32. return;
  33. }
  34. }
  35.  
  36. output.Text = "Yes! It's prime with probability " + ((long)1 - ((long)1 / Math.Pow(2, k)));
  37. }
  38.  
  39. //This is O(n^3). You have at most O(n) levels of recursion and the multiplication in the recursion is O(n^2)
  40. private long Modexp(int x, long e, long N)
  41. {
  42. if (e == 0)
  43. return 1;
  44. long z = Modexp(x, e/2, N); //Note: C# integer division automatically floors
  45. if (e % 2 == 0) return (z * z) % N;
  46. else return (x * ((z * z) % N)) % N;
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement