Cod sursa(job #15903)

Utilizator dryaAdriana Velicu drya Data 11 februarie 2007 20:47:55
Problema Fractii Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 0.96 kb
#include <stdio.h>

#define NMax 1000001

char is[NMax];
unsigned int n;
unsigned long long tot[NMax];

void ciur() {
int i,j,k;
 for (i=2; i<=n; i++) {
  if (is[i]==0)  // i==nr prim
   for (j=2*i; j<=n; j+=i)
    is[j]=1; // j nu e nr prim
 }
}

unsigned long long totient(unsigned int x) {
int i,j=0,k,pow=1;
unsigned long long l=1;
 if (is[x]==0) return x-1; // daca x nr prim, return x-1
 k=x;
 if (k%2==0) { // x == 2^j * k, k>=1
  while (k>1 && k%2==0) {
   j++; k/=2;
  }
  return (1<<(j-1))*tot[k]; // return 2^(j-1) * totient[k]
 }
 for (i=3; is[i]==0 && k%i!=0; i+=2) {;}
 while (k>1 && k%i==0) {
  j++; k/=i;
 }
 for (l=1; l<j; l++)
  pow *= i;
 return (i-1)*pow*tot[k]; 
}

int main() {
int i;
FILE * fin = fopen("fractii.in","r");
FILE * fout = fopen("fractii.out","w");

 fscanf(fin,"%ld",&n);
 ciur();
 tot[1]=1;
 tot[0]=1;
 for (i=2; i<=n; i++) {
  tot[i] = totient(i);
  tot[0] += 2*tot[i];
 }
 fprintf(fout,"%ld\n",tot[0]);
 fclose(fin);
 fclose(fout);
 return 0;
}