Cod sursa(job #15926)

Utilizator dryaAdriana Velicu drya Data 11 februarie 2007 21:11:58
Problema Fractii Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 0.98 kb
#include <stdio.h>

#define NMax 1000001

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

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

unsigned int totient(unsigned int x) {
unsigned int i,j=0,k, l=1,pow=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; k%i!=0; i+=2) {;}
 while (k>1 && k%i==0) {
  j++; k/=i;
 }
 for (l=1; l<j; l++)
  pow *= i;
 return ((unsigned int)(i-1))*pow*((unsigned int)tot[k]); 
}

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

 fscanf(fin,"%d",&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,"%lld\n",tot[0]);
 fclose(fin);
 fclose(fout);
 return 0;
}