How to find the first 3 powers of 2 whose leading digits are 12 in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>
#include <string>
#include <vector>

// return true if 2^n starts with prefix, else false
bool startsWithPrefix(long long n, int prefix) {
    static const double log2v = std::log10(2.0);

    double x = n * log2v;
    double frac = x - std::floor(x);

    // count digits in prefix
    int digits = std::to_string(prefix).size();

    // compute leading digits
    int leading = static_cast<int>(std::pow(10, frac + digits - 1));

    return leading == prefix;
}

int main() {
    int prefix = 12;
    std::vector<long long> results;

    for (long long n = 1; results.size() < 3; n++) {
        if (startsWithPrefix(n, prefix)) {
            results.push_back(n);
        }
    }

    std::cout << "First 3 powers of 2 starting with " << prefix << ":\n";
    for (long long n : results) {
        std::cout << "n = " << n << " : ";
        std::cout << "2 ^ " << n << " = " << std::pow(2, n) << "\n";
    }
}


/*

First 3 powers of 2 starting with 12:
n = 7 : 2 ^ 7 = 128
n = 80 : 2 ^ 80 = 1.20893e+24
n = 90 : 2 ^ 90 = 1.23794e+27

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...