Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- class Test { // check Carmichael's totient function conjecture
- // We might call the phi function repeatedly with the same argument
- // To avoid repeaing the calculation we memoize it
- // IOW remember values previously calculated, in this Map
- static Map<Integer, Integer> map = new HashMap<>();
- static int gcd(int a, int b) { // find GCD by Euclid's algorithm
- while (b != 0) {
- int t = b;
- b = a % b;
- a = t;
- }
- return a;
- }
- static int phi(int n) {
- Integer value = map.get(n); // look in map
- if (value == null) // not worked out before
- { // work out now
- int count = 0;
- for (int k = 1; k <= n; k++) {
- if (gcd(n, k) == 1) {
- count++;
- }
- }
- map.put(n, count); // put in map
- return count;
- } else // worked out before
- {
- return value;
- }
- }
- public static void main(String args[]) throws Exception {
- for (int n = 1; n < 100; n++) {
- int m = 1;
- int target = phi(n);
- while (true) { // until we find it
- if (n == m) { // must have n and m distinct
- {
- m++;
- continue;
- }
- }
- if (phi(m) == target) { // if found out
- System.out.println("n = " + n + " m = " + m + " phi(n)=" + target);
- break; // next n
- }
- m++; // try next m
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment