51nod 1040 Greatest common divisor and (Euler function)

Source: Internet
Author: User
Tags greatest common divisor

1040 Greatest Common Divisor Source: rihkddd Base time limit: 1 seconds space limit: 131072 KB score: 80 Difficulty: 5 level algorithm problem collection attention to give a N, ask 1-n this n number, with the greatest common divisor of N. For example: n = 61,2,3,4,5,6 the same as 6 greatest common divisor, respectively, is 1,2,3,2,1,6, add together = Input
1 number N (n <= 10^9)
Output
Sum of the number of conventions
Input example
6
Output example
15
Idea: The aim is to seek ∑ (i= 1,n) gcd (i, n); gcd (i, N) = x, which means that x is a factor of N. Slightly deformed gcd (i/x, n/x) = 1, see this equation can think of Euler function, that is, to find a smaller than n/x and its coprime number. Because these books and n/x coprime, multiply X and N greatest common divisor only X. That is, we first find out each factor, and then calculate how much each factor contributes.
/** author:sweat123 * Created time:2016/6/27 14:01:46 * File Name:main.cpp*/#include<Set>#include<map>#include<queue>#include<stack>#include<cmath>#include<string>#include<vector>#include<cstdio>#include<time.h>#include<cstring>#include<iostream>#include<algorithm>#defineINF 1<<30#defineMOD 1000000007#definell Long Long#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1#definePi ACOs (-1.0)using namespacestd;Const intMAXN =1000000;intn;ll EF (intN) {ll cnt=N; inti;  for(i =2; I * I <= N; i++){         if(n% i = =0) {CNT-= cnt/i;//(X-X/P1) * (1-1/P2) * (1-1/P3) * (1-1/P4) .....             while(n% i = =0) n/=i; }     }    if(N >1) CNT-= CNT/N; returnCNT;} intMain () { while(~SCANF ("%d",&N)) {ll ans=0;  for(inti =1; I <= (int) sqrt (n); i++){            if(n% i = =0) {ans+ = EF (n/i) *i; if(n/i! =i) {ans+ = EF (i) * (N/i); }}} printf ("%lld\n", ans); }    return 0;}

51nod 1040 Greatest common divisor and (Euler function)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.