Cod sursa(job #1246695)

Utilizator mgntMarius B mgnt Data 21 octombrie 2014 15:48:55
Problema Sum Scor 95
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

bool
solveSum
()
{ bool  ok;
  
  ::std::ifstream  is("sum.in");
  ::std::size_t  n;
  is >> n;
  
  // Queries.
  ::std::vector < ::std::size_t >  X(n);
  ::std::size_t  i;
  ::std::size_t  x;
  ::std::size_t  m = 2;
  for(i=0; n>i; ++i)
  { is >> x;
    ok = (2 <= x);
    if( !ok)
    { ::std::runtime_error  exc("Invalid input.");
      throw exc;
    }
    m = ::std::max(m, x);
    X.at(i) = x;
  }
  
  ok = is.good();
  if( !ok)
  { ::std::runtime_error  exc("Invalid input.");
      throw exc;
  }
  
  // Erastotene's Sieve.
  ::std::vector < int >  f(m, 0);
  f.push_back(0);
  ::std::size_t  s;
  for(i=2; m >= i; ++i)
  { if(0 == f.at(i)  )
    { for(s = i; m >= s; s += i)
      { f[s] = i;
      }
    }
  }
  
  // Euler's Totient Function.
  ::std::size_t  p;
  ::std::size_t  a;
  ::std::size_t  b;
  for(i=2; m >= i; ++i)
  { p = f.at(i);
    a = 1;
    b = i;
    while(0 == (b % p)  )
    { a *= p;
      b /= p;
    }
    if( (1 == a) || (1 == b)  )
    { f[i] = i - (i/p);
    }
    else
    { f[i] = f[a] * f[b];
    }
  }
  
  // Answers.
  ::std::ofstream  os("sum.out");
  ::std::size_t  z;
  unsigned long long  w;
  for(i=0; n>i; ++i)
  { x = X[i];
    z = f[x];
    w  = x;
    w *= z;
    w *= 2;
    os << w << '\n';
  }
  
  return true; // Success.
}

int
main
()
{ int  status;
  try
  { bool  const ok = solveSum();
    status = ( ok ? 0 : 1 );
  }
  catch ( ... )
  { status = 2;
  }
  return status;
}