ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
BigInteger.h
Go to the documentation of this file.
1/*--------------------------------------------------------------------------*/
2/*--------------------------- File BigInteger.h ----------------------------*/
3/*--------------------------------------------------------------------------*/
131/*--------------------------------------------------------------------------*/
132/*----------------------------- DEFINITIONS --------------------------------*/
133/*--------------------------------------------------------------------------*/
134
135#ifndef __ADS_BigInteger
136 #define __ADS_BigInteger
137/* self-identification: #endif constant */
138
139/*--------------------------------------------------------------------------*/
140/*------------------------------ INCLUDES ----------------------------------*/
141/*--------------------------------------------------------------------------*/
142
143#include "ADS/Contract.h"
144#include "ADS/Portable.h"
145#include "ADS/Wide.h"
146
147#include <algorithm>
148#include <bit>
149#include <compare>
150#include <concepts>
151#include <cstddef>
152#include <cstdint>
153#include <initializer_list>
154#include <memory>
155#include <string>
156#include <utility>
157#include <vector>
158
159// the backend of GMP, with ADS_WITH_GMP: every operation goes to the mpn
160// and mpz layers of GMP, on the digits of BigInteger as they are; only
161// where a limb of GMP has 64 bits, all of them number, else BigInteger
162// stays on the code of the book
163#if defined( ADS_WITH_GMP )
164 #include <cstring>
165 #include <gmp.h>
166 #if ! defined( ADS_BIGINT_GMP ) && ( GMP_LIMB_BITS == 64 ) && \
167 ( GMP_NAIL_BITS == 0 )
168 #define ADS_BIGINT_GMP 1
169 #endif
170#endif
171#ifndef ADS_BIGINT_GMP
172 #define ADS_BIGINT_GMP 0
173#endif
174
175/*--------------------------------------------------------------------------*/
176/*--------------------------- NAMESPACE ------------------------------------*/
177/*--------------------------------------------------------------------------*/
178
179namespace ADS
180{
181
182namespace detail
183{
184
185/*--------------------------------------------------------------------------*/
186/*----------------------------- CLASS Limbs --------------------------------*/
187/*--------------------------------------------------------------------------*/
188
195class Limbs
196{
197
198 public:
199 using T = std::uint64_t;
200
202 Limbs( void ) noexcept { }
204 explicit Limbs( std::size_t n ) { resize( n ); }
206 Limbs( std::size_t n , T v ) { resize( n , v ); }
208 Limbs( const T * b , const T * e ) {
209 reserve( std::size_t( e - b ) );
210 std::copy( b , e , f_p );
211 f_n = std::size_t( e - b );
212 }
214 Limbs( std::initializer_list< T > l ) : Limbs( l.begin() , l.end() ) { }
216 Limbs( const Limbs & o ) : Limbs( o.f_p , o.f_p + o.f_n ) { }
218 Limbs( Limbs && o ) noexcept { take( o ); }
220 Limbs & operator=( const Limbs & o ) {
221 if( this != &o ) {
222 if( o.f_n > f_cap ) { // the new block first
223 T * q = std::allocator< T >().allocate( o.f_n );
224 release();
225 f_p = q;
226 f_cap = o.f_n;
227 }
228 std::copy( o.f_p , o.f_p + o.f_n , f_p );
229 f_n = o.f_n;
230 }
231 return( *this );
232 }
234 Limbs & operator=( Limbs && o ) noexcept {
235 if( this != &o ) {
236 release();
237 take( o );
238 }
239 return( *this );
240 }
241 ~Limbs( void ) { release(); }
242
244 [[nodiscard]] std::size_t size( void ) const { return( f_n ); }
246 [[nodiscard]] bool empty( void ) const { return( f_n == 0 ); }
248 T * data( void ) { return( f_p ); }
250 const T * data( void ) const { return( f_p ); }
252 T * begin( void ) { return( f_p ); }
254 T * end( void ) { return( f_p + f_n ); }
256 const T * begin( void ) const { return( f_p ); }
258 const T * end( void ) const { return( f_p + f_n ); }
260 T & operator[]( std::size_t i ) { return( f_p[ i ] ); }
262 const T & operator[]( std::size_t i ) const { return( f_p[ i ] ); }
264 T & back( void ) { return( f_p[ f_n - 1 ] ); }
266 const T & back( void ) const { return( f_p[ f_n - 1 ] ); }
267
269 void reserve( std::size_t n ) {
270 if( n > f_cap )
271 regrow( std::max( n , 2 * f_cap ) );
272 }
274 void resize( std::size_t n , T v = 0 ) {
275 reserve( n );
276 if( n > f_n )
277 std::fill( f_p + f_n , f_p + n , v );
278 f_n = n;
279 }
281 void assign( std::size_t n , T v ) {
282 f_n = 0;
283 resize( n , v );
284 }
286 void push_back( T v ) {
287 reserve( f_n + 1 );
288 f_p[ f_n++ ] = v;
289 }
291 void pop_back( void ) { --f_n; }
292
294 friend bool operator==( const Limbs & a , const Limbs & b ) {
295 return( ( a.f_n == b.f_n ) && std::equal( a.f_p , a.f_p + a.f_n , b.f_p ) );
296 }
297
298 private:
299 static constexpr std::size_t kIn = 2;
300
302 void regrow( std::size_t c ) {
303 T * q = std::allocator< T >().allocate( c );
304 std::copy( f_p , f_p + f_n , q );
305 release();
306 f_p = q;
307 f_cap = c;
308 }
310 void release( void ) noexcept {
311 if( f_p != f_in ) {
312 std::allocator< T >().deallocate( f_p , f_cap );
313 f_p = f_in;
314 f_cap = kIn;
315 }
316 }
319 void take( Limbs & o ) noexcept {
320 f_n = o.f_n;
321 f_cap = o.f_cap;
322 if( o.f_p != o.f_in )
323 f_p = o.f_p;
324 else {
325 std::copy( o.f_in , o.f_in + o.f_n , f_in );
326 f_p = f_in;
327 }
328 o.f_p = o.f_in;
329 o.f_n = 0;
330 o.f_cap = kIn;
331 }
332
333 T * f_p = f_in;
334 std::size_t f_n = 0 ,
335 f_cap = kIn;
336 T f_in[ kIn ] = {};
337
338 }; // end( class Limbs )
339
340} // end( namespace detail )
341
342/*--------------------------------------------------------------------------*/
343/*--------------------------- CLASS BigInteger -----------------------------*/
344/*--------------------------------------------------------------------------*/
345
348{
349
350/*--------------------------------------------------------------------------*/
351 public:
352 using Limb = std::uint64_t;
353
354 // the lengths, in digits of the shorter factor, from which the code of
355 // the book multiplies by Karatsuba and by the NTT: round numbers near
356 // where each method overtakes the one before, not tuned to a processor,
357 // the backend of GMP being the fast route
358 static constexpr std::size_t kKaratsuba = 32;
359 static constexpr std::size_t kFFT = 4096;
360
362 BigInteger( long long v = 0 );
363
383 explicit BigInteger( const std::string & s , int base = 10 );
384
405 [[nodiscard]] std::string toString( int base = 10 ) const;
406
410 [[nodiscard]] std::string toStringSchool( int base = 10 ) const;
416 static BigInteger fromStringSchool( const std::string & s , int base = 10 );
417
419 [[nodiscard]] int sign( void ) const;
421 [[nodiscard]] BigInteger abs( void ) const;
422
424 [[nodiscard]] std::size_t limbs( void ) const;
425
426#if defined( ADS_WITH_GMP )
429 static BigInteger fromGmp( mpz_srcptr z );
430
433 template< class Z >
434 requires requires( const Z & z ) {
435 { z.get_mpz_t() } -> std::convertible_to< mpz_srcptr >;
436 }
437 explicit BigInteger( const Z & z )
438 : BigInteger( fromGmp( z.get_mpz_t() ) ) { }
439
442 void toGmp( mpz_ptr z ) const;
443
446 template< class Z >
447 requires requires( Z & z ) {
448 { z.get_mpz_t() } -> std::convertible_to< mpz_ptr >;
449 }
450 [[nodiscard]] Z toGmp( void ) const {
451 Z z;
452 toGmp( z.get_mpz_t() );
453 return( z );
454 }
455#endif
456
458 BigInteger operator-( void ) const;
461 friend BigInteger operator+( const BigInteger & a , const BigInteger & b );
464 friend BigInteger operator-( const BigInteger & a , const BigInteger & b );
480 friend BigInteger operator*( const BigInteger & a , const BigInteger & b );
483 friend BigInteger operator/( const BigInteger & a , const BigInteger & b );
486 friend BigInteger operator%( const BigInteger & a , const BigInteger & b );
494 friend bool operator==( const BigInteger & a ,
495 const BigInteger & b ) = default;
498 friend std::strong_ordering operator<=>( const BigInteger & a ,
499 const BigInteger & b );
500
507 static std::pair< BigInteger , BigInteger > divMod( const BigInteger & a ,
508 const BigInteger & b );
509
533 static std::pair< BigInteger , BigInteger >
534 divModSchool( const BigInteger & a , const BigInteger & b );
535
554 const BigInteger & b );
576 const BigInteger & b );
617 static BigInteger multiplyFFT( const BigInteger & a , const BigInteger & b );
618
623 static BigInteger divExact( BigInteger a , const BigInteger & b );
624
626 static void addMul( BigInteger & r , const BigInteger & a ,
627 const BigInteger & b );
628
645 static BigInteger pow( const BigInteger & x , unsigned long n );
646
653 static std::pair< BigInteger , BigInteger > sqrtRem( const BigInteger & a );
658 static BigInteger sqrt( const BigInteger & a );
659
677 static BigInteger sqrtNewton( const BigInteger & a );
678
704 static BigInteger gcd( const BigInteger & a , const BigInteger & b );
705
719
720/*--------------------------------------------------------------------------*/
721 private:
722 using Mag = detail::Limbs;
723
726 static constexpr std::size_t kNTTMax = std::size_t( 1 ) << 25;
727
730 enum class Method {
731 AUTO ,
732 SCHOOL ,
733 KARATSUBA ,
734 FFT
735 };
736
738 BigInteger( bool neg , Mag d );
739
741 static void trim( Mag & d );
743 static int compareMag( const Mag & a , const Mag & b );
744
747 static Limb addN( Limb * r , const Limb * a , std::size_t na ,
748 const Limb * b ,
749 std::size_t nb );
752 static Limb subN( Limb * r , const Limb * a , std::size_t na ,
753 const Limb * b ,
754 std::size_t nb );
756 static Limb addMul1( Limb * r , const Limb * a , std::size_t n , Limb m );
758 static Limb subMul1( Limb * r , const Limb * a , std::size_t n , Limb m );
759
761 static Mag addMag( const Mag & a , const Mag & b );
763 static Mag subMag( const Mag & a , const Mag & b );
765 static BigInteger addSigned( const BigInteger & a , const BigInteger & b ,
766 bool bneg );
767
770 static void mulMag( Mag & r , const Mag & a , const Mag & b ,
771 Method how = Method::AUTO );
774 static BigInteger product( const BigInteger & a , const BigInteger & b ,
775 Method how );
777 static void mulSchool( Limb * r , const Limb * a , std::size_t na ,
778 const Limb * b , std::size_t nb );
781 static std::size_t mulScratch( std::size_t n );
786 static void mulRec( Limb * r , const Limb * a , std::size_t na ,
787 const Limb * b ,
788 std::size_t nb , Method how , Limb * w );
790 static Mag mulNTT( const Limb * a , std::size_t na , const Limb * b ,
791 std::size_t nb );
792
795 static Limb divSmall( Mag & a , Limb d );
797 static void mulAddSmall( Mag & a , Limb m , Limb c );
800 static std::pair< Mag , Mag > divModMag( const Mag & u , const Mag & v ,
801 bool school );
802
805 static void figures( Mag a , int base , std::string & out );
806
808 static std::uint64_t gcdWord( std::uint64_t a , std::uint64_t b );
810 static Mag gcdLehmer( Mag u , Mag v );
811
812#if ADS_BIGINT_GMP
814 static mpz_srcptr gmpView( mpz_t z , const Limb * d , std::size_t n );
816 static mpz_srcptr gmpView( mpz_t z , const BigInteger & x );
818 static BigInteger gmpNumber( mpz_srcptr z );
820 static BigInteger gmpTake( mpz_ptr z );
821#endif
822
823 friend class Rational;
824
826 [[nodiscard]] bool normal( void ) const;
827
828 bool f_neg = false;
829 Mag f_d;
830
831 }; // end( class BigInteger )
832
833/*--------------------------------------------------------------------------*/
834
835} // end( namespace ADS )
836
837/*--------------------------------------------------------------------------*/
838/*-------------------------- IMPLEMENTATION --------------------------------*/
839/*--------------------------------------------------------------------------*/
840
841#include "ADS/numeric/impl/BigInteger.tpp"
842
843/*--------------------------------------------------------------------------*/
844
845#endif /* BigInteger.h included */
846
847/*--------------------------------------------------------------------------*/
848/*------------------------- End File BigInteger.h --------------------------*/
849/*--------------------------------------------------------------------------*/
The contracts of ADS: the preconditions, the postconditions and the invariants of the operations,...
The primitives of the processor that the compilers spell each in their own way, in one form for all: ...
The arithmetic of two words that C++20 does not spell, in one form for every compiler: the product of...
an integer of any length, sign and magnitude in base
Definition BigInteger.h:348
friend std::strong_ordering operator<=>(const BigInteger &a, const BigInteger &b)
the order of and , by the signs, the lengths and the digits from the most significant
static std::pair< BigInteger, BigInteger > sqrtRem(const BigInteger &a)
the integer square root and : by mpn_sqrtrem() with the backend, else by sqrtNewton()
std::string toStringSchool(int base=10) const
the figures of toString() by the code of the book, with no backend,
std::size_t limbs(void) const
the number of digits (limbs) in base
friend class Rational
Definition BigInteger.h:823
static BigInteger multiplyKaratsuba(const BigInteger &a, const BigInteger &b)
the product by Karatsuba at every length down to factors of fewer than 4 digits, which Algorithm M mu...
BigInteger(const std::string &s, int base=10)
the number written in in the base, with an optional sign
friend bool operator==(const BigInteger &a, const BigInteger &b)=default
true if the two numbers are equal
BigInteger & operator-=(const BigInteger &b)
the difference into
static BigInteger sqrt(const BigInteger &a)
the root of sqrtRem(), with no remainder
BigInteger(long long v=0)
the number
static constexpr std::size_t kFFT
limbs for the NTT
Definition BigInteger.h:359
static BigInteger gcdEuclid(BigInteger a, BigInteger b)
the greatest common divisor of and , by Euclid
friend BigInteger operator*(const BigInteger &a, const BigInteger &b)
the product , by the method of the length of the factors
static BigInteger multiplyFFT(const BigInteger &a, const BigInteger &b)
the product by the number theoretic transform at every length
BigInteger abs(void) const
the absolute value
BigInteger & operator*=(const BigInteger &b)
the product into
friend BigInteger operator%(const BigInteger &a, const BigInteger &b)
the remainder of divMod(), of the sign of
static BigInteger multiplySchool(const BigInteger &a, const BigInteger &b)
the product by Algorithm M,
static BigInteger fromStringSchool(const std::string &s, int base=10)
the number of the constructor from a string by the code of the book, with no backend,...
static std::pair< BigInteger, BigInteger > divModSchool(const BigInteger &a, const BigInteger &b)
the quotient and the remainder by Algorithm D,
int sign(void) const
the sign, , 0 or 1
friend BigInteger operator-(const BigInteger &a, const BigInteger &b)
the difference , as the sum with the sign of changed
std::string toString(int base=10) const
the figures of the number in the base, with a sign if negative
static BigInteger pow(const BigInteger &x, unsigned long n)
the power , by mpz_pow_ui() with the backend, else by the binary method
static BigInteger gcd(const BigInteger &a, const BigInteger &b)
the greatest common divisor of and , by mpz_gcd() with the backend, else by Lehmer
std::uint64_t Limb
a digit, in base
Definition BigInteger.h:352
static void addMul(BigInteger &r, const BigInteger &a, const BigInteger &b)
static std::pair< BigInteger, BigInteger > divMod(const BigInteger &a, const BigInteger &b)
the quotient truncated toward zero and the remainder, by Algorithm D [see divModSchool()] or by the b...
friend BigInteger operator/(const BigInteger &a, const BigInteger &b)
the quotient truncated toward zero
BigInteger operator-(void) const
the opposite
static BigInteger sqrtNewton(const BigInteger &a)
the integer square root by Newton's method from above
BigInteger & operator+=(const BigInteger &b)
the sum into
friend BigInteger operator+(const BigInteger &a, const BigInteger &b)
the sum , by Algorithm 4.3.1A on the magnitudes of the same sign and 4.3.1S on those of opposite sign...
static constexpr std::size_t kKaratsuba
limbs for Karatsuba
Definition BigInteger.h:358
static BigInteger divExact(BigInteger a, const BigInteger &b)
the quotient for a divisor of , by mpz_divexact() with the backend, else as
constexpr detail::Reserve reserve
room for items in : s.reserve( n ), else reserve( s , n ) found by ADL, else nothing (the builders)
Definition Capabilities.h:444
Definition ADT.h:96