Ansichten: QuotePaste - CodePaste - NoPaste
Codesnippet eingetragen am 16.4.2013 um 22:25
Von: Michael
Sprache: Java
Beschreibung:
CodeSnippet:
  1. package Crypto;
  2.  
  3. import java.util.Scanner;
  4.  
  5. /**
  6.  *
  7.  * @author Михайл Скиба <michael.skiba@rub.de>
  8.  */
  9. public class Crypto {
  10.  
  11. public static void main(String args[]) {
  12. while (true) {
  13. int a, p, remainder = 0, counter = 0;
  14. System.out.println("Please enter a");
  15. Scanner scanner = new Scanner(System.in);
  16. a = scanner.nextInt();
  17. System.out.println("Please enter p (must be prime)");
  18. scanner = new Scanner(System.in);
  19. p = scanner.nextInt();
  20.  
  21. if (!isPrime(p)) {
  22. System.out.println(p + " is not a prime number!");
  23. System.exit(0);
  24. }
  25.  
  26. do {
  27. counter++;
  28. if (counter == 1) {
  29. remainder = a;
  30. } else {
  31. remainder = (remainder * a) % p;
  32. }
  33. /* Debug-Line: System.out.printf("%d^%d = %d mod %d\n", a, counter, remainder, p); */
  34. } while (remainder != 1);
  35. System.out.printf("ord(%d)= %d", a, counter);
  36. if (counter == (p - 1)) {
  37. System.out.printf(" (%d is a primitiv element)", a);
  38. }
  39.  
  40. System.out.printf("\nContinue y?\n");
  41. scanner = new Scanner(System.in);
  42. if (!scanner.nextLine().equalsIgnoreCase("y")) {
  43. System.exit(0);
  44. }
  45. }
  46. }
  47.  
  48. // Shamelessly stolen from the interwebs ...
  49. // http://stackoverflow.com/questions/2385909/what-would-be-the-fastest-method-to-test-for-primality-in-java
  50. public static boolean isPrime(int n) {
  51. return !new String(new char[n]).matches(".?|(..+?)\\1+");
  52. }
  53. }
  54.