1. 程式人生 > >EularProject 70:Totient permutation

EularProject 70:Totient permutation

Euler’s Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
The number 1 is considered to be relatively prime to every positive number, so φ(1)=1.

Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180.

Find the value of n, 1 < n < 107, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.

參考程式碼:

#include <iostream>
using namespace std;

#define MAX 10000
#define TAR 10000000

bool state[MAX] = { 0
}; int pri[MAX] = { 0 }; int cnt = 0; double check(int im, int in) { int i, m = im, n = in; int cnt1[10] = { 0 }; int cnt2[10] = { 0 }; while (m > 0) { cnt1[m % 10]++; m /= 10; } while (n > 0) { cnt2[n % 10]++; n /= 10; } for (i = 0; i < 10; i++) { if
(cnt1[i] != cnt2[i]) { break; } } if (i == 10) { return (double)im / in; }else { return TAR; } } int main() { double result = TAR; int n = 0; for (int i = 2; i < MAX; i++) { state[i] = 1; pri[i] = 0; } for (int i = 2; i < MAX; i++) { if (state[i] == 1) { for (int j = 2 * i; j < MAX; j += i) { state[j] = 0; } pri[cnt] = i; cnt++; } } for (int i = 2; i < cnt; i++) { for (int j = i + 1; j < cnt; j++) { if (pri[i] * pri[j] < TAR) { double temp = check(pri[i] * pri[j], (pri[i] - 1)*(pri[j] - 1)); if (temp < result) { result = temp; n = pri[i] * pri[j]; } } } } cout << n << endl; return 0; }