G - Harmonic Number (II) LightOJ - 1245 (暴力打表找规律?)

题意:
给了一个代码,让计算 i = 1 n n i , n的范围比较大为 2 31


题解:
显然暴力过不去,那么我们肯定会感到和sqrt有关系,于是我们去打表发现 2 31 = 46341 , 并不是很大,然后我们去枚举每个数字的 n i , 发现一个规律,首先对于小于 n 的数字大力能得到结果,然后其他的数字发现如果数字i出现则他的出现次数为( n i n i + 1 ),然后根据公式进行计算即可。


AC代码:

#include <iostream>
#include <stdio.h>
#include <set>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>

using namespace  std;
typedef long long ll;
const int maxn = 1e7 + 10;
const ll inf = 0x3f3f3f3f;
typedef long double ld;
#define met(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define per(i, a, b) for(int i = a; i >= b; i--)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
inline ll mul(ll x, ll y, ll mod) {ll res = (x * y - (ll)(ld)(x / mod * y + 1e-8) * mod); return res < 0 ? res + mod : res;}
const double PI = acos(-1.0);
const int mod = 1000;
ll qPow(ll base, ll n) {ll res = 1; while(n) {if(n & 1) res = (res * base); base = (base * base); n >>= 1;} return res;}
vector<int> prime;
bool vis[maxn];
long long H( int n ) {
    long long res = 0;
    for( int i = 1; i <= n; i++ )
        res = res + n / i;
    return res;
}
int main() {
    //cout << sqrt(qPow(2, 31)) << endl;
    ll n;
    int T, cas = 1;
    scanf("%d", &T);
    while(T--) {
        scanf("%lld", &n);
        ll res = 0, tmp = sqrt(n);
        rep(i, 1, tmp) {
            res += n / i;
        }
        rep(i, 1, tmp) {
            res += i * (n / i - n / (i + 1));
        }
        if(tmp == n / tmp) {
            res -= tmp;
        }
        printf("Case %d: %lld\n",cas++, res);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_38081836/article/details/81490030
今日推荐