How to convert unlimited binary to decimal length

The most common way is to get a power of 2 for each nonzero position of a binary number, and then sum them up. This does not work when the binary number is huge, say

10000 ... 0001 // 1,000,000 positions

Unable to let the computer calculate pow (2,1000000). Thus, the traditional method does not work.

Another way to do this?

Can someone give an arithmetic calculation method, not a library?

+3
source share
6 answers

happydave, ( GMP). - , . , bigint.

10 ^ (2 ^ n) , . , :

Select the largest value in your cache smaller than your remaining number, store this
in a working variable.
do{
  Multiply it by the next largest value in your cache and store the result in a
  temporary value.
  If the new value is still smaller, set your working value to this number (swapping 
  references here rather than allocating new memory is a good idea),
  Keep a counter to see which digit you're at. If this changes by more than one
  between instances of the outer loop, you need to pad with zeros
} Until you run out of cache
This is your next base ten value in binary, subtract it from your binary number while
the binary number is larger than your digit, the number of times you do this is the 
decimal digit -- you can cheat a little here by comparing the most significant bits
and finding a lower bound before trying subtraction.
Repeat until your binary number is 0

O (n ^ 4) O (nlog (n)) . , n ^ 4 n ^ 3, .

+2

( , ), (*, pow ..). google "++ " - , .

+1

pow (2,1000000). , .

. , Python ( ). Python , .

++ ( C) GMP. , . ++-, ( , pow() ++).

++, GMP:

#include <iostream>
#include <gmpxx.h>

int main(int, char *[])
{
    mpz_class a, b;
    a = 2;
    mpz_pow_ui(b.get_mpz_t(), a.get_mpz_t(), 1000000);
    std::string s = b.get_str();
    std::cout << "length is " << s.length() << std::endl;
    return 0;
}

length is 301030

0,18 .

+1

" O (n ^ 4) O (nlog (n)) ". O (n ^ (2 + epsilon)) ( n - ) O (n) : N - n. mod 2 (, ) mod 5 (, , , mod 5 4- 9 .). mod 2 5, . ; 10 (-, ), , .

+1

2 ** 1000000 9.3 Smalltalk, . Smalltalk .

2 raisedToInteger: 1000000

, , . MOD 10 DIV 10, ( ).

:

LargeInteger *a;
char *string;


while (a != 0) {
    int remainder;
    LargeInteger *quotient;

    remainder = a % 10.
    *string++ = remainder + 48.
    quotient = a / 10.
    } 

( ), , , .

0

It is quite simple with the Gnu Multiprecision Library . Unfortunately, I could not test this program because it seems to me that I need to rebuild my library after updating the compiler. But there is not much room for error!

#include "gmpxx.h"
#include <iostream>

int main() {
    mpz_class megabit( "1", 10 );
    megabit <<= 1000000;
    megabit += 1;
    std::cout << megabit << '\n';
}
0
source

All Articles