Fu_L's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Fu-L/cp-library

:heavy_check_mark: kth_root_integer
(src/math/kth_root_integer.hpp)

kth_root_integer

unsigned long long kth_root_integer(unsigned long long x, int k)

$\lfloor \sqrt[k]{x} \rfloor$ を返します.

計算量

Depends on

Verified with

Code

#pragma once
#include "../template/template.hpp"
unsigned long long kth_root_integer(const unsigned long long x, const int k) {
    if(k <= 1) return k ? x : 1;
    if(x <= 1) return x;
    if(k >= 64) return 1;
    auto check = [&](unsigned long long a) -> bool {
        unsigned long long power = 1;
        for(int i = k; i;) {
            if(i & 1) {
                if(power > x / a) return false;
                power *= a;
            }
            if(i >>= 1) {
                if(a > x / a) return false;
                a *= a;
            }
        }
        return power <= x;
    };
    unsigned long long res = pow(x, 1.0 / k);
    while(!check(res)) --res;
    while(check(res + 1)) ++res;
    return res;
}
#line 2 "src/template/template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<long long, long long>;
#define rep(i, a, b) for(long long i = (a); i < (b); ++i)
#define rrep(i, a, b) for(long long i = (a); i >= (b); --i)
constexpr long long inf = 4e18;
struct SetupIO {
    SetupIO() {
        ios::sync_with_stdio(0);
        cin.tie(0);
        cout << fixed << setprecision(30);
    }
} setup_io;
#line 3 "src/math/kth_root_integer.hpp"
unsigned long long kth_root_integer(const unsigned long long x, const int k) {
    if(k <= 1) return k ? x : 1;
    if(x <= 1) return x;
    if(k >= 64) return 1;
    auto check = [&](unsigned long long a) -> bool {
        unsigned long long power = 1;
        for(int i = k; i;) {
            if(i & 1) {
                if(power > x / a) return false;
                power *= a;
            }
            if(i >>= 1) {
                if(a > x / a) return false;
                a *= a;
            }
        }
        return power <= x;
    };
    unsigned long long res = pow(x, 1.0 / k);
    while(!check(res)) --res;
    while(check(res + 1)) ++res;
    return res;
}
Back to top page