From 67842d9aa934d3f71fdfa806eb688197841ee095 Mon Sep 17 00:00:00 2001 From: Dev-XYS Date: Fri, 13 Jan 2017 12:50:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=AC=A7=E6=8B=89=E5=87=BD=E6=95=B0=E7=9A=84?= =?UTF-8?q?=E7=BA=BF=E6=80=A7=E7=AD=9B=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Euler's-Totient-Function-Sieve(Linear).cpp | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Euler's-Totient-Function-Sieve(Linear).cpp diff --git a/Euler's-Totient-Function-Sieve(Linear).cpp b/Euler's-Totient-Function-Sieve(Linear).cpp new file mode 100644 index 0000000..bc33283 --- /dev/null +++ b/Euler's-Totient-Function-Sieve(Linear).cpp @@ -0,0 +1,47 @@ +#include + +#define MAX_ELEMENT 100000000 + +using namespace std; + +int prime[MAX_ELEMENT], pc, div[MAX_ELEMENT], phi[MAX_ELEMENT]; + +void sieve(int n) +{ + phi[1] = 1; + for (int i = 2; i <= n; i++) + { + if (div[i] == 0) + { + prime[pc++] = i; + div[i] = i; + phi[i] = i - 1; + } + for (int j = 0; j < pc; j++) + { + if (i * prime[j] > n) break; + div[i * prime[j]] = prime[j]; + if (i % prime[j] == 0) + { + phi[i * prime[j]] = phi[i] * prime[j]; + break; + } + else + { + phi[i * prime[j]] = phi[i] * (prime[j] - 1); + } + } + } +} + +int main() +{ + int n; + scanf("%d", &n); + sieve(n); + for (int i = 1; i <= n; i++) + { + printf("phi(%d) = %d\n", i, phi[i]); + } + return 0; +}