waltermilner

Untitled

May 10th, 2016
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. class Test { // check Carmichael's totient function conjecture
  5.  
  6.   // We  might call the phi function repeatedly with the same argument
  7.   // To avoid repeaing the calculation we memoize it
  8.   // IOW remember values previously calculated, in this Map
  9.   static Map<Integer, Integer> map = new HashMap<>();
  10.  
  11.   static int gcd(int a, int b) { // find GCD by Euclid's algorithm
  12.     while (b != 0) {
  13.       int t = b;
  14.       b = a % b;
  15.       a = t;
  16.     }
  17.     return a;
  18.   }
  19.  
  20.   static int phi(int n) {
  21.     Integer value = map.get(n); // look in map
  22.     if (value == null) // not worked out before
  23.     { // work out now
  24.       int count = 0;
  25.       for (int k = 1; k <= n; k++) {
  26.         if (gcd(n, k) == 1) {
  27.           count++;
  28.         }
  29.       }
  30.       map.put(n, count); // put in map
  31.       return count;
  32.     } else // worked out before
  33.     {
  34.       return value;
  35.     }
  36.   }
  37.  
  38.   public static void main(String args[]) throws Exception {
  39.     for (int n = 1; n < 100; n++) {
  40.       int m = 1;
  41.       int target = phi(n);
  42.       while (true) { // until we find it
  43.         if (n == m) { // must have n and m distinct
  44.           {
  45.             m++;
  46.             continue;
  47.           }
  48.         }
  49.         if (phi(m) == target) { // if found out
  50.           System.out.println("n = " + n + " m = " + m + " phi(n)=" + target);
  51.           break; // next n
  52.         }
  53.         m++; // try next m
  54.       }
  55.     }
  56.   }
  57.  
  58. }
Add Comment
Please, Sign In to add comment