IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C++ Discussion :

Problème de récursion


Sujet :

C++

  1. #1
    Invité
    Invité(e)
    Par défaut Problème de récursion
    Salut, étant donné que je voudrais dépendre le moins possible de librairies, j'ai décidé de coder mes propres classes, afin de ré-inventer des plus petites roues, mais sans perte de performance.

    C'est alors que je suis tombé sur ce tutoriel qui m'a l'air bien pour la gestion des grands nombres, il présente même un code source écrit en Ocalm :

    http://damien-guichard.developpez.co...l/?page=page_6

    Malheureusement en ayant retranscrit tout sont code en c++, je me retrouve avec un problème de reste qui est toujours null.

    Le .h
    Code cpp : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
     
    #ifndef BIG_INT_HPP
    #define BIG_INT_HPP
    #include <string>
    #include <vector>
    #include <iostream>
    #include <limits>
    #include "../../../include/odfaeg/Math/maths.h"
    namespace odfaeg {
        class BigInt {
        public :
            BigInt(const std::string& number);
            BigInt(unsigned long long integer=0, bool positif=true, unsigned int b=10);
            static BigInt generate (int nbBits, unsigned int base=2);
            bool isPositif();
            BigInt operator+(const BigInt& bi) const;
            BigInt operator+=(const BigInt& bi);
            BigInt operator-(const BigInt& bi) const;
            BigInt operator-=(const BigInt& bi);
            BigInt operator*(const BigInt& bi) const;
            BigInt operator*=(const BigInt& bi);
            BigInt operator/(const BigInt& bi) const;
            BigInt operator/=(const BigInt& bi);
            BigInt operator%(const BigInt& bi) const;
            BigInt operator%=(const BigInt& bi);
            bool operator== (const BigInt& bi ) const;
            bool operator!= (const BigInt& bi ) const;
            bool operator<= (const BigInt& bi ) const;
            bool operator< (const BigInt& bi ) const;
            bool operator>= (const BigInt& bi ) const;
            bool operator> (const BigInt& bi ) const;
            BigInt operator<< (int n) const;
            BigInt operator>> (int n) const;
            BigInt operator& (int n) const;
            BigInt operator-() const;
            BigInt pow (BigInt exp);
            BigInt prodMod (const BigInt &b, const BigInt &n) const;
            BigInt modOfPow (const BigInt exp, const BigInt mod) const;
            bool isNull() const;
            unsigned int getNbChiffres();
            BigInt convert(unsigned int base) const;
        private :
            static const unsigned int karatsuba_treshold = 20;
            void computeNbC(unsigned long long int c);
            BigInt scaleUp (unsigned int n) const;
            BigInt scaleDown (unsigned long long int n, BigInt &r) const;
            BigInt arraySub (int n, int length) const;
            BigInt addZeros(unsigned int n);
            void insert (unsigned int c, int pos);
            unsigned int operator[](unsigned int i) const;
            void shorten();
            void clear();
            unsigned int size() const;
            BigInt add(const BigInt& bi) const;
            BigInt sub(const BigInt& bi) const;
            int   comparaison(const BigInt& b) const;
            BigInt operator++(int i);
            BigInt operator--(int i);
            BigInt multiply(const BigInt& bi) const;
            BigInt karatsuba(const BigInt& bi) const;
            BigInt burnikel_ziegler (const BigInt& bi, BigInt &r) const;
            std::vector<unsigned int> chiffres;
            unsigned int base;
            unsigned long long int nbChiffres;
            bool positif;
            static unsigned int cmpt;
            friend char symbole( unsigned int valeur, unsigned int base);
            friend std::ostream& operator<< (std::ostream& out, const BigInt& bi);
        };
    }
    #endif // BIG_INT

    Le .cpp
    Code cpp : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
     
    #include "../../../include/odfaeg/Network/bigInt.hpp"
     
    using namespace std;
    namespace odfaeg {
        unsigned int BigInt::cmpt = 0;
        BigInt::BigInt(const std::string& number) {
            base = 10;
            positif = (number.at(number.length()-1) != '-') ? true : false;
            nbChiffres = (positif) ? number.length() : number.length() - 1;
            for (unsigned int i = 0; i < nbChiffres; i++) {
                unsigned int c = number.at(i) - 48;
                if (c >= 0 && c < 10)
                    chiffres.push_back(c);
            }
        }
        BigInt::BigInt(unsigned long long integer, bool positif, unsigned int b) {
            this->positif = positif;
            this->base = b;
            nbChiffres = 0;
            if (integer > 0) {
                if (base < std::numeric_limits<unsigned int>::max()) {
                    unsigned long long int max = 1LL;
                    while (integer >= max)
                        max *= base;
                    max /= base;
                    while (max > 0) {
                        unsigned long long int c;
                        c = integer / max;
                        computeNbC(c);
                        chiffres.push_back(c);
                        integer %= max;
                        max /= b;
                    }
                } else {
                    unsigned long long int c = integer / base;
                    computeNbC(c);
                    chiffres.push_back(c);
                    integer %= base;
                    computeNbC(integer);
                    chiffres.push_back(integer);
                }
            }
        }
        void BigInt::computeNbC (unsigned long long int c) {
            unsigned int nb = base;
            unsigned int i = 1;
            while (c >= nb) {
                nb *= base;
                i++;
            }
            nbChiffres += i;
        }
        unsigned int BigInt::getNbChiffres() {
            return nbChiffres;
        }
        BigInt BigInt::generate (int nbBits, unsigned int base) {
            unsigned int nearestPowerOfTwo = math::Math::logn(base, 2);
            base = math::Math::power(2, nearestPowerOfTwo);
            BigInt n;
            n.nbChiffres = (nearestPowerOfTwo == 1) ? base : nbBits / base * nearestPowerOfTwo;
            do {
                 for (int i = 0; i < n.nbChiffres; i++) {
                     unsigned int c = math::Math::random(base-1);
                     n.insert(c, 0);
                 }
     
             } while (n.isNull());
             n.shorten();
             return n;
        }
     
        bool BigInt::isPositif () {
            return positif;
        }
        void BigInt::shorten () {
     
            vector<unsigned int>::iterator it;
            for (it = chiffres.begin(); it != chiffres.end(); ) {
                if (*it == 0) {
                    it = chiffres.erase(it);
                    nbChiffres--;
                } else
                    break;
            }
        }
        void BigInt::clear()
        {
            chiffres.clear();
        }
        bool BigInt::isNull() const {
            return chiffres.empty();
        }
        unsigned int BigInt::size() const {
            return chiffres.size();
        }
        unsigned int BigInt::operator[] ( unsigned int i ) const {
            return ( i<0 || i>=chiffres.size() ? 0 : chiffres[i] );
        }
        BigInt BigInt::operator++ (int i) {
     
            for(int i= chiffres.size() - 1; i>= 0; i-- ) {
                if (chiffres[i] == base -1)
                    chiffres[i]= 0;
                else {
                    ++(chiffres[i]);
                    return *this;
                }
     
            }
            insert (1,  0);
            return *this;
        }
        void BigInt::insert(unsigned int c, int pos) {
     
            if (pos <= size()) {
                BigInt result(0, true, base);
                result.chiffres.resize(size() + 1, 0);
                for (int i = 0, j = 0; i <= size(); i++, j++) {
                    if (i != pos) {
                        result.chiffres[i] = chiffres[j];
                    } else {
                        j--;
                    }
                }
                result.chiffres[pos] = c;
                computeNbC(c);
                *this = result;
            }
        }
        BigInt BigInt::operator-- (int i) {
            bool ok = false;
            for(int i=chiffres.size() - 1; i>=0; i--)
                if (chiffres[i] == 0)
                    chiffres[i]= base - 1;
                else {
                    --(chiffres[i]);
                    shorten();
                    ok = true;
                }
            if (!ok)
                cerr<<"Error : negative number"<<endl;
            return *this;
        }
        int BigInt::comparaison (const BigInt &b) const {
            if ( chiffres.size() > b.chiffres.size() )
                return +1;
            if ( chiffres.size() < b.chiffres.size() )
                return -1;
     
            for(unsigned int i= 0; i < chiffres.size(); i++) {
     
                if ( chiffres[i] > b.chiffres[i] )
                    return +1;
                if ( chiffres[i] < b.chiffres[i] )
                    return -1;
            }
            return 0;
        }
        bool BigInt::operator== ( const BigInt& a ) const {
            return ( comparaison(a) == 0 );
        }
        bool BigInt::operator!= ( const BigInt& a) const {
            return ( comparaison(a) != 0 );
        }
        bool BigInt::operator< ( const BigInt& a ) const {
            return ( comparaison(a) < 0 );
        }
        bool BigInt::operator<= ( const BigInt& a ) const {
            return ( comparaison(a) <= 0 );
        }
        bool BigInt::operator> ( const BigInt& a) const {
            return ( comparaison(a) > 0 );
        }
        bool BigInt::operator>= ( const BigInt& a) const {
            return ( comparaison(a) >= 0 );
        }
        BigInt BigInt::operator-() const {
            BigInt result = *this;
            result.positif = !positif;
            return result;
        }
        BigInt BigInt::add (const BigInt& bi) const {
            if (isNull())
                return bi;
            if (bi.isNull())
                return *this;
            BigInt somme(0, true, base);
            somme.clear();
            unsigned int taille = max(this->size(), bi.size())+1;
            somme.chiffres.resize( taille, 0);
     
            unsigned int retenue= 0;
            int i, j;
            for(i=size() - 1, j = bi.size() - 1; i >= 0; i--, j--)  {
     
                unsigned long long int temp = (unsigned long long int) (*this)[i] + (unsigned long long int) bi[j] + (unsigned long long int) retenue;
     
                if ( temp < base) {
                    somme.chiffres[i] = (unsigned int) temp;
                    retenue = 0;
                }
                else {
                    somme.chiffres[i]= (unsigned int) temp - base;
                    retenue = 1;
                }
            }
     
            while (retenue != 0) {
                if (i >= 0) {
                    unsigned long long int temp = (unsigned long long int) (*this)[i] + (unsigned long long int) bi[i] + (unsigned long long int) retenue;
     
                    if ( temp < base) {
                        somme.chiffres[i] = (unsigned int) temp;
                        retenue = 0;
                    } else {
                        somme.chiffres[i]= (unsigned int) temp - base;
     
                    }
                    i--;
                } else {
                    somme.insert(retenue, 0);
                    retenue = 0;
                }
            }
            somme.shorten();
            return somme;
        }
     
        BigInt BigInt::operator+ (const BigInt &bi) const {
            BigInt a = *this;
            BigInt b = bi;
            BigInt result(0, true, base);
            if (positif && bi.positif) {
                if (bi.size() > size()) {
                    a = bi;
                    b = *this;
                }
                result = a.add(b);
            } else if (!positif && bi.positif) {
                if (*this >= bi) {
                    result = a.sub(b);
                    result.positif = false;
                } else {
                    result = b.sub(a);
                }
            } else if (positif && !bi.positif) {
                if (*this >= bi) {
                    result = a.sub(b);
                } else {
                    result = b.sub(a);
                    result.positif = false;
                }
            } else {
               if (bi.size() > size()) {
                    a = bi;
                    b = *this;
               }
               result = a.add(b);
               result.positif = false;
            }
            return result;
        }
        BigInt BigInt::operator+= (const BigInt &bi) {
            *this = *this + bi;
            return *this;
        }
        BigInt BigInt::sub (const BigInt &bi) const {
            BigInt diff(0, true, this->base);
            diff.clear();
     
            if (bi.isNull())
                return *this;
     
            unsigned int taille= max( this->size(), bi.size() );
            diff.chiffres.resize( taille, 0);
            // Calculer la somme chiffre par chiffre en tenant compte des retenues
            unsigned int retenue= 0;
            int i, j;
            for(i=size() - 1, j = bi.size() - 1; i>=0; i--, j--)  {
                long long temp = (long long) ((unsigned long long int) (*this)[i] - (unsigned long long int) bi[j] - (unsigned long long int) retenue);
     
                if ( temp >= 0 ) {
                    diff.chiffres[i]= (unsigned int) temp;
                    retenue = 0;
                }
                else {
                    diff.chiffres[i]= (unsigned int) (temp + base);
                    retenue = 1;
                }
            }
            while (retenue > 0) {
                long long int temp = (long long int) ((unsigned long long int) (*this)[i] - (unsigned long long int) retenue);
     
                if ( temp >= 0 ) {
                    diff.chiffres[i]= (unsigned int) temp;
                    retenue = 0;
                }
                else {
                    //std::cout<<*this<<" "<<bi<<" "<<diff.size()<<" "<<i<<std::endl;
                    diff.chiffres[i]= (unsigned int) (temp + base);
                }
                i--;
            }
            diff.shorten();
            return diff;
        }
        BigInt BigInt::operator- (const BigInt &bi) const {
            BigInt result(0, true, base);
            BigInt a = *this;
            BigInt b = bi;
            if (positif && bi.positif) {
                if (*this >= bi) {
                    result = a.sub(b);
                } else {
                    result = b.sub(a);
                    result.positif = false;
                }
            } else if (!positif && bi.positif) {
                if (bi.size() > size()) {
                    a = bi;
                    b = *this;
                }
                result = a.add(b);
                result.positif = false;
            } else if (positif && !bi.positif) {
                if (bi.size() > size()) {
                    a = bi;
                    b = *this;
                }
                result = a.add(b);
            } else {
                if (*this >= bi) {
                    result = a.sub(b);
                    result.positif = false;
                } else {
                    result.positif = true;
                    result = b.sub(a);
                }
            }
            return result;
        }
        BigInt BigInt::operator-= (const BigInt &bi) {
            *this = *this - bi;
            return *this;
        }
        BigInt BigInt::addZeros (unsigned int n) {
     
            if (n < 0)
                return *this;
            if (isNull())
                return *this;
            BigInt result(0, positif, base);
     
            result.chiffres.resize(size() + n, 0);
            nbChiffres += n;
            for (int i = 0; i < size(); i++) {
                 result.chiffres[i] = chiffres[i];
            }
            return result;
        }
        BigInt BigInt::multiply (const BigInt &bi) const {
     
            BigInt produit(0, true, this->base);
            produit.clear();
            if ( this->size() == 0 || bi.size() == 0 ) {
                return produit;
            }
     
            int i = 0, j = bi.size() - 1;
            produit = scaleUp(bi.chiffres[i]).addZeros(j);
     
            while ( j > 0)
            {
               i++; j--;
               produit += scaleUp (bi.chiffres[i]).addZeros(j);
     
            }
     
            produit.shorten();
            return produit;
        }
        BigInt BigInt::karatsuba (const BigInt &bi) const {
            if (size() >= bi.size()) {
                unsigned int n = size() / 2;
                BigInt a = arraySub(0, size() - n);
                BigInt b = arraySub(size() - n, n);
                if (bi.size() > n) {
                    BigInt c = bi.arraySub(0, bi.size() - n);
                    BigInt d = bi.arraySub(bi.size() - n, n);
                    BigInt ac = a * c;
                    BigInt bd = b * d;
                    BigInt ad_bc = (a + b) * (c + d) - ac - bd;
                    ac = ac.addZeros(2*n);
                    ad_bc = ad_bc.addZeros(n);
                    return ac + ad_bc + bd;
                } else {
                    BigInt aq = a * bi;
                    BigInt bq = b * bi;
                    aq = aq.addZeros(n);
                    return aq + bq;
                }
            }
            return *this;
        }
        BigInt BigInt::operator* (const BigInt &bi) const {
            // D´el´eguer les petites multiplications `a la m´ethode scolaire
     
            BigInt result(0, true, base);
            if (size() < bi.size())
                result = bi * *this;
            else if (bi.size() < karatsuba_treshold)
                result = multiply(bi);
            else
                result = karatsuba(bi);
            if (!positif && bi.positif || positif && !bi.positif)
                result.positif = false;
            else
                result.positif = true;
            return result;
        }
        BigInt BigInt::operator*= (const BigInt &bi) {
            *this = *this * bi;
            return *this;
        }
     
     
        BigInt BigInt::operator/ (const BigInt &bi) const {
            if (bi == 0) {
                cerr<<"Error : b is null!";
                return 0;
            }
            if (bi > *this) {
                std::cout<<"greater!"<<std::endl;
                return 0;
            }
            cmpt = 0;
            BigInt result(0, true, base);
            BigInt reste(0, true, base);
            result = burnikel_ziegler(bi, reste);
            if (!positif && bi.positif || positif && !bi.positif)
                result.positif = false;
            else
                result.positif = true;
            return result;
     
        }
        BigInt BigInt::operator/= (const BigInt &bi) {
            *this = *this / bi;
            return *this;
        }
     
        BigInt BigInt::operator% (const BigInt& bi) const {
     
            if (bi == BigInt(0)) {
                cerr<<"Error : b is null!";
                return 0;
            }
            if (bi > *this)
                return *this;
            BigInt reste(0, true, base);
            burnikel_ziegler(bi, reste);
            reste.shorten();
            if (!positif && bi.positif || positif && !bi.positif)
                reste.positif = false;
            else
                reste.positif = true;
            return reste;
        }
        BigInt BigInt::pow (BigInt exp) {
            BigInt un(1, true, base);
            BigInt deux (2, true, base);
            if (exp.isNull()) {
                return un;
            } else if (exp % deux == 0) {
                BigInt a = pow(exp / deux);
                return (a * a);
            } else {
                return (*this) * pow (exp - un);
            }
        }
        BigInt BigInt::prodMod (const BigInt &b, const BigInt &n) const {
          if(isNull()) {
            return 0;
          } else {
            // a = 2 * q  + e
            BigInt q = *this / BigInt(2);
            BigInt e = *this % BigInt(2);
            BigInt r = BigInt(2) * q.prodMod(b, n) % n;
            return e == 0 ? r : (r + b) % n;
          }
        }
        BigInt BigInt::modOfPow (const BigInt exp, const BigInt mod) const {
            BigInt result = 1;
     
            BigInt e = exp, bs;
            bs = *this;
            while (e > 0) {
     
                if (e % 2 == 1)
                    result = result * bs % mod;
                e /= 2;
                bs = bs * bs % mod;
            }
            return result;
        }
        BigInt BigInt::operator%= (const BigInt &bi) {
            *this = *this % bi;
            return *this;
        }
        BigInt BigInt::arraySub (int n, int length) const {
            BigInt result(0, true, this->base);
     
            if (n >= 0 && n + length < size() && length  > 0) {
                result.chiffres.resize(length, 0);
                for (int i = n, j = 0; j < length; i++, j++) {
                    result.chiffres[j] = chiffres[i];
                }
            }
     
            result.shorten();
            return result;
        }
        BigInt BigInt::operator<< (int n) const {
            if (n < 0)
                return *this;
            if (isNull())
                return *this;
            BigInt result(0, true, base);
     
            result.chiffres.resize(size() + n, 0);
            for (int i = 0; i < size(); i++) {
                 result.chiffres.push_back(chiffres[i]);
            }
            return result;
        }
        BigInt BigInt::operator>> (int n) const {
            if (n < 0)
                return *this;
            if (isNull())
                return *this;
            if (n > size())
                n = size();
            BigInt result (0, true, base);
            result.chiffres.resize(size() - n, 0);
            for (int i = 0; i < result.size(); i++)
                result.chiffres[i] = chiffres[i];
            return result;
        }
        BigInt BigInt::operator& (int n) const {
            BigInt a, b, bi(n);
            if (size() > bi.size()) {
                b = bi<<(size() - bi.size() - 1);
                a = *this;
            } else if (size() < bi.size()) {
                a = *this<<(bi.size() - size() - 1);
                b = bi;
            } else {
                a = *this;
                b = bi;
            }
            BigInt result (0, true, base);
            result.chiffres.resize(a.size(), 0);
            for (int i = 0; i < a.size(); i++) {
                result.chiffres[i] = chiffres[i] & b.chiffres[i];
            }
            result.shorten();
            return result;
        }
        BigInt BigInt::scaleUp (unsigned int n) const {
     
            unsigned long long int accu = 0;
            unsigned int retenue = 0;
            BigInt result(0, true, base);
            result.chiffres.resize(size() + 1, 0);
            BigInt bs = BigInt(base, true, base);
            BigInt ni(n);
     
            if (ni >= 0 && ni < bs) {
                if (n == 0)
                    return 0;
                for (int i = size(); i > 0; i--) {
                    accu = (unsigned long long) chiffres[i-1] * n + (unsigned long long) retenue;
                    result.chiffres[i] = (unsigned int) (accu % base);
                    retenue = (unsigned int) (accu / base);
                }
                result.chiffres[0] = retenue;
                if (retenue == 0)
                    result.shorten();
            }
            return result;
        }
        BigInt BigInt::scaleDown (unsigned long long int n, BigInt& r) const {
     
            unsigned long long int accu = 0;
            unsigned int retenue = 0;
            BigInt result = *this;
            if (n >= 0 && n < base * base) {
                for (unsigned int i = 0; i < size(); i++) {
                    accu = (unsigned long long) chiffres[i] + (unsigned long long int) retenue * base;
                    result.chiffres[i] = (unsigned int) (accu / n);
                    retenue = (unsigned int) (accu % n);
                }
     
            }
            if((int) chiffres.size() -1 > 0 && result.chiffres[0] == 0)
                result.arraySub(1,chiffres.size()-1);
            r = BigInt(retenue, true, base);
            result.shorten();
            return result;
        }
        BigInt BigInt::burnikel_ziegler(const BigInt &bi, BigInt &r) const {
     
            BigInt q(0, true, base);
            if (bi.size() <= 2) {
                unsigned long long int b2 = (bi.size() < 2) ? bi.chiffres[0] : bi.chiffres[0] * base + bi.chiffres[1];
                q = scaleDown(b2, r);
                r.shorten();
                std::cout<<r<<std::endl;
                return q;
            }
            unsigned int n = (bi.size() - 1) / 2;
     
            // D´ecouper a et b en deux moiti´es
            BigInt a0, a1;
            a0 = arraySub(size() - n, n);
            a1 = arraySub(0, size() - n);
            if (a1 >= bi) {
     
                BigInt q1, r1, q0, r0;
                q1 = a1.burnikel_ziegler (bi, r1);
                r1 = r1.addZeros(n);
                q0 = (r1 + a0).burnikel_ziegler (bi, r0);
                r = r0;
                std::cout<<r<<std::endl;
                q1 = q1.addZeros(n);
                return q1 + q0;
            } else {
     
                BigInt b0, b1, q1, r1, a0_r1, b0_q1;
                b0 = bi.arraySub(bi.size() - n, n);
                b1 = bi.arraySub(0, bi.size() - n);
                q1 = a1.burnikel_ziegler(b1, r1);
                r1 = r1.addZeros(n);
                a0_r1 = r1 + a0;
                b0_q1 = b0 * q1;
                if (a0_r1 >= b0_q1) {
                    r = a0_r1 - b0_q1;
                    std::cout<<r<<std::endl;
                    return q1;
                } else {
     
                    BigInt minus_x = b0_q1 - a0_r1;
                    r = bi - minus_x;
                    std::cout<<r<<std::endl;
                    return q1 - BigInt(1, true, base);
                }
            }
        } 
        // Op´erateur de sortie (afficher les chiffres, ou bien "0" pour une suite vide)
        ostream& operator<< ( ostream& out, const BigInt& bi) {
     
            if ( bi.size()== 0 ) return ( out << 0 );
            if (!bi.positif)
                    out<<"-";
            for( int i = 0; i < bi.size(); i++) {
     
                out<<bi.chiffres[i];
                if (i != bi.size()-1)
                    out<<".";
            }
            return out;
        }
    }

    et le main :
    Code cpp : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    using namespace odfaeg;
    int main(int argc, char* argv[])
    {
     
        BigInt a("14854849864651546445948594812659685156164165");
        BigInt b("2565498645123159652135");
        BigInt c = a % b;
    }

    A chaque fois que je remontedans la récursion, r vaut 0, le reste de la division vaut donc toujours 0 ce qui n'est pas bon, par contre, pas de problèmes pour toutes les autres opérations!

    En même temps je n'ai jamais géré de fonction récursive avec plusieurs types de retour car ça n'existe pas en c++.

    Comment donc, changer la valeur de r dans la fonction de récursion pour que le r soit bon ?

    Merci d'avance.

  2. #2
    Membre éprouvé
    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2009
    Messages
    552
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mars 2009
    Messages : 552
    Points : 1 060
    Points
    1 060
    Par défaut
    Citation Envoyé par Lolilolight Voir le message
    Salut, étant donné que je voudrais dépendre le moins possible de librairies, j'ai décidé de coder mes propres classes, afin de ré-inventer des plus petites roues, mais sans perte de performance.
    Et tu crois que tu vas atteindre les performances de GMP avec tes roues carrées?

    Tu as une approche naïve où tes grands entiers sont représentés par des chiffres : Compare ça à ce que fait GMP avec ces "limb" pour exploiter au mieux les opérations du processeur.

  3. #3
    Invité
    Invité(e)
    Par défaut
    Bref peut importe les performances.

    En tout cas pour la division l'algorithme de ce tutoriel n'est pas bon :

    Code cpp : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    int main(int argc, char* argv[])
    {
     
        BigInt a("14854849864651546445948594812659685156164167");
        BigInt b("256484564516841685468468456486");
        BigInt d = a / b;
        BigInt r = a % b;
        std::cout<<"d : "<<d<<std::endl<<"r : "<<r<<std::endl<<"dividande : "<<d*b + r<<std::endl;
    }

    Vu que je ne retrouve pas le dividande de départ en multipliant par le diviseur et en ajoutant le reste.

  4. #4
    Invité
    Invité(e)
    Par défaut
    Ca y est j'ai trouvé ou était le soucis dans mon code, fallait que j'enlève les zéros non significatif dans la méthode arraySub, avant de copier la partie du tableau.

    Code cpp : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    BigInt BigInt::arraySub (int n, int length) const {
            const_cast<BigInt*>(this)->shorten();
            BigInt result(0, true, this->base);
            if (n >= 0 && n + length <= size() && length  > 0) {
                result.chiffres.resize(length, 0);
                for (int i = n, j = 0; j < length; i++, j++) {
                    result.chiffres[j] = chiffres[i];
                }
            }
            return result;
        }

    Donc le tutoriel est bon.

    Sinon, j'aimerais savoir maintenant comment optimiser ça au mieux, déjà c'est quoi des "limb" ?
    Je recherche également un algorithme de génération de nombre premiers très grand pour générer des clés!

    Merci d'avance.

  5. #5
    Membre émérite
    Avatar de prgasp77
    Homme Profil pro
    Ingénieur en systèmes embarqués
    Inscrit en
    Juin 2004
    Messages
    1 306
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur en systèmes embarqués
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Juin 2004
    Messages : 1 306
    Points : 2 466
    Points
    2 466
    Par défaut
    Je n'ai pas tout lu, je me suis arrêté à « récursion », « OCaml » et « retranscrire en C++ ». Et la je me suis dit aïe : il va y avoir un problème de taille ! Tu vas droit dans le mur car OCaml fait quelque chose que C++ ne fait pas : l'optimisation des fonctions à récursion terminale. Je te laisse découvrir ce dont il s'agit, et tu comprendras instantanément pourquoi utiliser les mêmes algos en C++ qu'en caml ne marchera pas.

    La bonne nouvelle, c'est qu'il est toujours possible de transformer un appel récursif terminal en équivalent itératif, en général sans perte de lisibilité. Bon courage.
    -- Yankel Scialom

  6. #6
    Membre éprouvé
    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2009
    Messages
    552
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mars 2009
    Messages : 552
    Points : 1 060
    Points
    1 060
    Par défaut
    Citation Envoyé par Lolilolight Voir le message
    Sinon, j'aimerais savoir maintenant comment optimiser ça au mieux, déjà c'est quoi des "limb" ?
    C'est un concept posé dans la bibliothèque GMP. En bref, au lieu de décomposer le nombre en entier de 0 à 9, tu le décomposes en entier de 32 ou 64 bits. Tu imagineras vite que le nombre d'opération n'est pas le même.

    Extrait simplifié de gmp.h où mpz_struct représente un grand entier :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    typedef unsigned int		mp_limb_t;
    typedef int			mp_limb_signed_t;
     
    typedef struct
    {
      int _mp_alloc;		/* Number of *limbs* allocated and pointed
    				   to by the _mp_d field.  */
      int _mp_size;			/* abs(_mp_size) is the number of limbs the
    				   last field points to.  If _mp_size is
    				   negative this is a negative number.  */
      mp_limb_t *_mp_d;		/* Pointer to the limbs.  */
    } __mpz_struct;

  7. #7
    gl
    gl est déconnecté
    Rédacteur

    Homme Profil pro
    Inscrit en
    Juin 2002
    Messages
    2 165
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 165
    Points : 4 637
    Points
    4 637
    Par défaut
    Citation Envoyé par prgasp77 Voir le message
    Tu vas droit dans le mur car OCaml fait quelque chose que C++ ne fait pas : l'optimisation des fonctions à récursion terminale.
    Dire que C++ ne fait pas telle ou telle optimisation n'a que peu de sens. Le standard n'impose pas les optimisations mais ne les interdit pas non plus, le choix est laissé à l'implémentation. Typiquement, gcc réalise la TCO s'il le peut lors de la compilation en O2 (il semblerait que Visual C++ la réalise également lorsque le niveau d'optimisation est suffisamment élevé).
    Est-ce une bonne idée de se reposer sur ces optimisations ? Il n'y a pas de réponse absolue, ça va dépendre du (ou des) compilateur utilisé, des paramètres de compilation utilisés et de la portabilité souhaitée.

  8. #8
    Invité
    Invité(e)
    Par défaut
    Ma classe permet de travailler avec n'importe quel base, 32, 64, 16, etc..., donc je pourrai très bien décomposer mes entiers en 32 ou en 64 bits.
    J'utilise juste une fonction de conversion de base, juste tester si ma classe fonctionne car c'est plus simple de le vérifier en base 10.

    Il y a juste que lors des calculs les deux nombres doivent être de même base évidement.

  9. #9
    Membre émérite
    Avatar de prgasp77
    Homme Profil pro
    Ingénieur en systèmes embarqués
    Inscrit en
    Juin 2004
    Messages
    1 306
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur en systèmes embarqués
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Juin 2004
    Messages : 1 306
    Points : 2 466
    Points
    2 466
    Par défaut
    Citation Envoyé par gl Voir le message
    Le [standard C++] n'impose pas les optimisations [...]. Est-ce une bonne idée de se reposer sur ces optimisations ? Il n'y a pas de réponse absolue, ça va dépendre du (ou des) compilateur utilisé, des paramètres de compilation utilisés et de la portabilité souhaitée.
    Tout à fait. Et c'est particulièrement vrai quand on écrit des outils ayant pour vocation de servir sur plusieurs projets .
    -- Yankel Scialom

Discussions similaires

  1. [Mapping] Problème dû à la récursion
    Par joploya dans le forum Hibernate
    Réponses: 0
    Dernier message: 03/10/2011, 11h25
  2. problème de récursion infinie
    Par leomaradan dans le forum Débuter
    Réponses: 1
    Dernier message: 01/10/2009, 11h42
  3. [SVG] Problème de récursion
    Par Kicker dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 09/11/2008, 17h17
  4. Réponses: 2
    Dernier message: 16/10/2008, 10h49
  5. Excel et publipostage ( problème de "récursion" )
    Par Clad3 dans le forum Macros et VBA Excel
    Réponses: 12
    Dernier message: 22/08/2007, 11h38

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo