LightOJ – 1236 Pairs Forming LCM

Pairs Forming LCM

把n进行质因数分解,设n的某个质因子为p,其指数为cnt.
对i和j包含的相同质因子p,设指数分别为a,b,由于LCM(i,j)=n,则有cnt=max(a,b).
a,b共有2*(cnt+1)-1种方案(乘以2是a,b互换,减1是剔除a=b的重复情况)

之后由乘法原理,得到了(i,j)的方案数res, 但其中包括了i>j的部分.i<j 和 i>j是对称的, 则 (res+1)/2就是题目要求的了.

#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

#define ll long long
using namespace std;
const int maxn = 1e7;
bool v[maxn + 1];
vector<int> prime;
void primes() {
  v[0] = v[1] = 1;
  for (int i = 2; i <= maxn; ++i) {
    if (!v[i]) {
      prime.push_back(i);
      for (int j = i; j <= maxn / i; ++j) {
        v[i * j] = 1;
      }
    }
  }
}

ll divide(ll n) {
  ll res = 1;
  for (int i = 0; i < prime.size(); ++i) {
    if (prime[i] > n) break;
    int t = 0;
    if (n % prime[i] == 0) {
      while (n % prime[i] == 0) {
        t++;
        n /= prime[i];
      }
      res *= 2 * (t + 1) - 1;
    }
  }
  if (n > 1) res *= 3;

  return (res + 1) / 2;
}

int main() {
  // freopen("in.txt","r",stdin);
  // freopen("out.txt","w",stdout);
  int T, kase = 0;
  primes();
  cin >> T;
  while (T--) {
    long long n;
    cin >> n;
    printf("Case %d: %lld\n", ++kase, divide(n));
  }
  return 0;
}