1. 程式人生 > >UVA 10820 Send a Table 數論 歐拉函數

UVA 10820 Send a Table 數論 歐拉函數

space nbsp ostream void 分享 cal 解題思路 for can

  題目鏈接: https://vjudge.net/problem/UVA-10820

  題目描述: 給你一個N, N <= 50000, 讓你尋找N之內互素數的個數

  解題思路: 歐拉函數, 由於位置顛倒是兩個解, 在小於N的範圍內只有(1, 1)x, y相等, 其他的都是不等的, 所以我們只需要算phi(2) + phi(3) + ...... phi(n), 然後 * 2 + 1即可

  代碼:

技術分享
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include 
<cstring> #include <iterator> #include <cmath> #include <algorithm> #include <stack> #include <deque> #include <map> #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 #define mem0(a) memset(a,0,sizeof(a)) #define meminf(a) memset(a,-0x3f,sizeof(a)) #define
fi(n) for(i=0;i<n;i++) #define fj(m) for(j=0;j<m;j++) #define sca(x) scanf("%d",&x) #define scalld(x) scanf("%I64d",&x) #define print(x) printf("%d\n", x) #define printlld(x) printf("%I64d\n",x) #define de printf("=======\n") #define yes printf("YES\n") #define no printf("NO\n") typedef
long long ll; using namespace std; const int maxn = 50000+100; int phi[maxn]; void phi_table( int n ) { for( int i = 2; i <= n; i++ ) { phi[i] = 0; } phi[1] = 1; for( int i = 2; i <= n; i++ ) { if( !phi[i] ) { for( int j = i; j <= n; j += i ) { if( !phi[j] ) phi[j] = j; phi[j] = phi[j] / i * (i-1); } } } } int main() { int n; mem0(phi); phi_table(50000); while( sca(n) == 1 && n ) { if( n == 1 ) { printf( "1\n" ); continue; } else { int res = 0; for( int i = 2; i <= n; i++ ) { res += phi[i]; } printf( "%d\n", 2 * res + 1 ); } } return 0; }
View Code

  思考: 歐拉函數, 復雜度為O(nlognlogn), 本題就是直接打表然後計算和, 要註意這種思想, 倍數可以直接得到就轉化成互素這種思想, 好好學數學

UVA 10820 Send a Table 數論 歐拉函數