Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35

Сложение чисел до определенного разряда

29.06.2018, 14:21. Показов 2116. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я рассчитываю числа Фибоначчи и нужны только первые 9 цифр от каждого числа, то есть все что после 9 цифры числа я не рассчитываю.

Вот мой полурабочий код

C++
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
struct BillionNum : public std::vector<unsigned>{
    static const unsigned MaxDigit = 1000000000;
 
    BillionNum(unsigned x){
        push_back(x); // первые 9 цифр
        push_back(x); // последние 9 цифр
    }
 
    // add a big number
    void operator+=(BillionNum& other){
        if (other[0] + (*this)[0] > MaxDigit){
            (*this)[0] /= 10;
            other[0] /= 10;
            (*this)[0] += other[0];
        }
        else (*this)[0] += other[0];
        (*this)[1] += other[1];
        (*this)[1] %= MaxDigit;
    }
};
 
int main(){
    BillionNum a = 1;
    BillionNum b = 1;
 
    for (unsigned int i = 2; i <= 330000; i++){
        a += b;
        swap(a, b);
    }
}
Первые 9 цифр 329468 числа в последовательности Фибоначчи 245681739, а в данном коде 245567184. Не спорю, что я что-то делаю не так или не до конца с переполнением первых 9 чисел. У меня чувство, что я забыл что-то еще прибавить вот здесь (*this)[0] += other[0]; и как мне кажется это что-то прибавлять нужно в каком-то особом случае...

Я пробовал увеличить количество нулей в MaxDigit и потом из 329468 числа брать только первые 9 путем деления на 10^(количество добавленных нулей). В таком случае переполнение не успевает добраться до 9 цифры, но это костыльное решение...
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
29.06.2018, 14:21
Ответы с готовыми решениями:

Функция: вернуть значение определенного разряда восьмибитного числа (номер разряда передается в качестве аргумента)
Написать функцию, которая возвращает значение определенного разряда восьмибитного числа. Номер разряда передается в качестве аргумента.

Посчитать количество работников определенного разряда
Мне надо считать количество работников определенного разряда, вот только не в excel, a в Google таблицах. поможете?

Функция: изменение значения определенного разряда восьмибитного числа на 1 и на 0 (остальные разряды не изменять)
Написать функции, изменяющие значение определенного разряда восьмибитного числа на 1 и на 0 (остальные разряды измениться не должны). Номер...

9
475 / 427 / 290
Регистрация: 10.03.2015
Сообщений: 1,782
29.06.2018, 14:29
Простите, а что в Вашем понимании числа Фибоначчи? Примерно 41 число в его последовательности имеет более (или =) 9 цифр. Поясните на конкретных примерах, что Вы делаете.
0
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35
29.06.2018, 14:40  [ТС]
Числа Фибоначчи это когда каждое следующие число это сумма двух предыдущих. Я начинаю с чисел 1 и 1 как и многие то есть 1 1 2 3 5 8 13 21 ...
Я беру только первые 9 цифр этого числа.
Например, когда последовательность доходит до 44 числа в перегрузке оператора происходит вот что
44 701408733 <-- f1
45 113490317(0) <-- f2
if f2 > maxdigit then f1 /= 10; f2 /= 10; f3 = f1 + f2; end if;
46 183631190(3)

Под 45 числом я написал псевдокод, мы делим оба слагаемых на 10 если их сумма больше миллиарда и только потом складываем их иначе просто складываем. В скобках отсекаемое число. В этом примере все так как оно должно быть, но на деле числа получаются немного меньше.
0
475 / 427 / 290
Регистрация: 10.03.2015
Сообщений: 1,782
29.06.2018, 14:54
Не могу вспомнить автора, но где-то на просторах форума находится. Изменить лишь вывод от .. до
C++
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
#define _CRT_SECURE_NO_WARNINGS
#include <vector>
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <cstring>
#include <cstdio>
#include <cstdlib>
 
class BigInteger
{
public:
    BigInteger()
    {
        _data.push_back(0);
    }
 
    BigInteger(long long x)
    {
        while (x)
        {
            _data.push_back(x % _base);
            x /= _base;
        }
 
        if (_data.empty()) _data.push_back(0);
    }
 
    BigInteger(unsigned long long x)
    {
        while (x)
        {
            _data.push_back(x % _base);
            x /= _base;
        }
 
        if (_data.empty()) _data.push_back(0);
    }
 
    BigInteger(int x) : BigInteger((long long)x) {}
    BigInteger(unsigned int x) : BigInteger((unsigned long long)x) {}
    BigInteger(short x) : BigInteger((long long)x) {}
    BigInteger(unsigned short x) : BigInteger((unsigned long long)x) {}
    BigInteger(char x) : BigInteger((long long)x) {}
    BigInteger(unsigned char x) : BigInteger((unsigned long long)x) {}
 
    BigInteger(std::string &s)
    {
        for (int i = (int)s.size(); i > 0; i -= 9)
            if (i < 9)
                _data.push_back(atoi(s.substr(0, i).data()));
            else
                _data.push_back(atoi(s.substr(i - 9, 9).data()));
 
        while (_data.size() > 1 && _data.back() == 0)
            _data.pop_back();
    }
 
    BigInteger(const char *s)
    {
        std::string d = s;
 
        for (int i = (int)d.size(); i > 0; i -= 9)
            if (i < 9)
                _data.push_back(atoi(d.substr(0, i).data()));
            else
                _data.push_back(atoi(d.substr(i - 9, 9).data()));
 
        while (_data.size() > 1 && _data.back() == 0)
            _data.pop_back();
    }
 
    BigInteger(const BigInteger& b)
    {
        _data.resize(b._data.size());
        std::copy(b._data.begin(), b._data.end(), _data.begin());
    }
 
    void ToString(char *s) const
    {
        sprintf(s, "%d", _data.empty() ? 0 : _data.back());
        for (int i = (int)_data.size() - 2; i >= 0; i--)
            sprintf(s, "%s%09d", s, _data[i]);
    }
 
    std::string ToString() const
    {
        char *buff = (char*)malloc(20);
 
        sprintf(buff, "%d", _data.empty() ? 0 : _data.back());
        std::string res = buff;
 
        for (int i = (int)_data.size() - 2; i >= 0; i--)
        {
            sprintf(buff, "%09d", _data[i]);
            res += buff;
        }
 
        free(buff);
 
        return res;
    }
 
    friend const BigInteger operator+(BigInteger &i);
    friend const BigInteger& operator++(BigInteger &i);
    friend const BigInteger& operator--(BigInteger &i);
    friend const BigInteger operator++(BigInteger &i, int);
    friend const BigInteger operator--(BigInteger &i, int);
 
    friend const BigInteger operator+(const BigInteger &c, const BigInteger &b);
    friend const BigInteger operator-(const BigInteger &c, const BigInteger &b);
    friend const BigInteger operator*(const BigInteger &a, const BigInteger &b);
    friend const BigInteger operator/(const BigInteger &a, const BigInteger &b);
    friend const BigInteger operator%(const BigInteger &a, const BigInteger &b);
 
    friend BigInteger& operator+=(BigInteger &a, const BigInteger &b);
    friend BigInteger& operator-=(BigInteger &a, const BigInteger &b);
    friend BigInteger& operator*=(BigInteger &a, const BigInteger &b);
    friend BigInteger& operator/=(BigInteger &a, const BigInteger &b);
    friend BigInteger& operator%=(BigInteger &a, const BigInteger &b);
 
    friend bool operator==(const BigInteger &a, const BigInteger &b);
    friend bool operator<=(const BigInteger &a, const BigInteger &b);
    friend bool operator>=(const BigInteger &a, const BigInteger &b);
    friend bool operator<(const BigInteger &a, const BigInteger &b);
    friend bool operator>(const BigInteger &a, const BigInteger &b);
    friend bool operator!=(const BigInteger &a, const BigInteger &b);
 
    /*operator long long() const
    {
    long long res = 0, b = 1;
    for(size_t i = 0; i < _data.size(); i++)
    {
    res += b * _data[i];
    b *= BigInteger::_base;
    }
    return res;
    }
 
    operator unsigned long long()
    {
    unsigned long long res = 0, b = 1;
    for(size_t i = 0; i < _data.size(); i++)
    {
    res += b * _data[i];
    b *= BigInteger::_base;
    }
    return res;
    }*/
 
    friend std::istream& operator >> (std::istream &is, BigInteger &i)
    {
        std::string s;
        is >> s;
        i = BigInteger(s);
        return is;
    }
 
    friend std::ostream& operator<<(std::ostream &os, const BigInteger &i)
    {
        os << i.ToString();
        return os;
    }
 
private:
    static const int _base = 1000 * 1000 * 1000;
    std::vector<int> _data;
 
    int _cmp(const BigInteger &a, const BigInteger &b) const //a - b, 1 if a > b
    {
        if (a._data.size() > b._data.size()) return 1;
        if (a._data.size() < b._data.size()) return -1;
 
        for (int i = (int)a._data.size() - 1; i >= 0; i--)
        {
            if (a._data[i] > b._data[i]) return 1;
            if (a._data[i] < b._data[i]) return -1;
        }
 
        return 0;
    }
 
    BigInteger _div_short(const BigInteger &c, int b, int &mod) const
    {
        mod = 0;
        BigInteger a = c;
        for (int i = (int)a._data.size() - 1; i >= 0; i--)
        {
            long long cur = a._data[i] + mod * 1ll * BigInteger::_base;
            a._data[i] = int(cur / b);
            mod = int(cur % b);
        }
 
        while (a._data.size() > 1 && a._data.back() == 0)
            a._data.pop_back();
 
        return a;
    }
 
    bool _is_zero() const
    {
        return _data.size() == 1 && _data[0] == 0;
    }
};
 
const BigInteger operator+(const BigInteger &i)
{
    return BigInteger(i);
}
 
const BigInteger& operator++(BigInteger &i)
{
    int j = 0;
    i._data[0]++;
 
    while (i._data[j] >= BigInteger::_base)
    {
        if (j == (int)i._data.size() - 1) i._data.push_back(1); else i._data[j + 1]++;
        i._data[j] -= BigInteger::_base;
        j++;
    }
 
    return i;
}
 
const BigInteger operator++(BigInteger &i, int)
{
    BigInteger old = BigInteger(i);
 
    int j = 0;
    i._data[0]++;
 
    while (i._data[j] >= BigInteger::_base)
    {
        if (j == (int)i._data.size() - 1) i._data.push_back(1); else i._data[j + 1]++;
        i._data[j] -= BigInteger::_base;
        j++;
    }
 
    return old;
}
 
//TODO: Optimize
const BigInteger& operator--(BigInteger &i)
{
    if (!i._is_zero()) i = i - 1;
    return i;
}
 
//TODO: Optimize
const BigInteger operator--(BigInteger &i, int)
{
    BigInteger old = BigInteger(i);
    if (!i._is_zero()) i = i - 1;
    return old;
}
 
const BigInteger operator+(const BigInteger &c, const BigInteger &b)
{
    BigInteger a = c;
 
    int carry = 0;
    for (size_t i = 0; i < std::max(a._data.size(), b._data.size()) || carry; i++)
    {
        if (i == a._data.size()) a._data.push_back(0);
        a._data[i] += carry + (i < b._data.size() ? b._data[i] : 0);
        carry = a._data[i] >= BigInteger::_base;
        if (carry) a._data[i] -= BigInteger::_base;
    }
 
    return a;
}
 
const BigInteger operator-(const BigInteger &c, const BigInteger &b)
{
    if (c < b) throw std::invalid_argument("a - b, a must b greater or equal zero");
    BigInteger a = c;
 
    int carry = 0;
    for (size_t i = 0; i < b._data.size() || carry; i++)
    {
        a._data[i] -= carry + (i < b._data.size() ? b._data[i] : 0);
        carry = a._data[i] < 0;
        if (carry) a._data[i] += BigInteger::_base;
    }
 
    while (a._data.size() > 1 && a._data.back() == 0)
        a._data.pop_back();
 
    return a;
}
 
const BigInteger operator*(const BigInteger &a, const BigInteger &b)
{
    BigInteger c;
    c._data.resize(a._data.size() + b._data.size());
 
    for (size_t i = 0; i < a._data.size(); i++)
        for (int j = 0, carry = 0; j < (int)b._data.size() || carry; j++)
        {
            long long cur = c._data[i + j] + a._data[i] * 1ll * (j < (int)b._data.size() ? b._data[j] : 0) + carry;
            c._data[i + j] = int(cur % BigInteger::_base);
            carry = int(cur / BigInteger::_base);
        }
 
    while (c._data.size() > 1 && c._data.back() == 0)
        c._data.pop_back();
 
    return c;
}
 
//TODO: Division by zero
const BigInteger operator/(const BigInteger &a, const BigInteger &b)
{
    if (b._is_zero()) throw std::invalid_argument("division by zero");
    BigInteger l = 0, r = a + 1, m;
    int t;
    while (r - l > 1)
    {
        //m = (r + l) / 2;
        m = a._div_short(r + l, 2, t);
        if (b * m <= a) l = m; else r = m;
    }
    return l;
}
 
const BigInteger operator%(const BigInteger &a, const BigInteger &b)
{
    if (b._is_zero()) throw std::invalid_argument("division by zero");
    BigInteger l = 0, r = a + 1, m;
    int t;
    while (r - l > 1)
    {
        //m = (r + l) / 2;
        m = a._div_short(r + l, 2, t);
        if (b * m <= a) l = m; else r = m;
    }
    return a - b * l;
}
 
BigInteger& operator+=(BigInteger &a, const BigInteger &b)
{
    int carry = 0;
    for (size_t i = 0; i < std::max(a._data.size(), b._data.size()) || carry; i++)
    {
        if (i == a._data.size()) a._data.push_back(0);
        a._data[i] += carry + (i < b._data.size() ? b._data[i] : 0);
        carry = a._data[i] >= BigInteger::_base;
        if (carry) a._data[i] -= BigInteger::_base;
    }
    return a;
}
 
BigInteger& operator-=(BigInteger &a, const BigInteger &b)
{
    int carry = 0;
    for (size_t i = 0; i < b._data.size() || carry; i++)
    {
        a._data[i] -= carry + (i < b._data.size() ? b._data[i] : 0);
        carry = a._data[i] < 0;
        if (carry) a._data[i] += BigInteger::_base;
    }
 
    while (a._data.size() > 1 && a._data.back() == 0)
        a._data.pop_back();
 
    return a;
}
 
BigInteger& operator*=(BigInteger &a, const BigInteger &b)
{
    a = a * b;
    return a;
}
 
BigInteger& operator/=(BigInteger &a, const BigInteger &b)
{
    a = a / b;
    return a;
}
 
BigInteger& operator%=(BigInteger &a, const BigInteger &b)
{
    a = a % b;
    return a;
}
 
bool operator==(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) == 0;
}
 
bool operator<=(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) <= 0;
}
 
bool operator>=(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) >= 0;
}
 
bool operator<(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) < 0;
}
 
bool operator>(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) > 0;
}
 
bool operator!=(const BigInteger& a, const BigInteger& b)
{
    return a._cmp(a, b) != 0;
}
 
int main()
{
    int n;
    std::cin >> n;
    std::vector<BigInteger> f = { BigInteger(0), BigInteger(1) };
    for (int i = 2; i <= n; i++) f.push_back(f[i - 1] + f[i - 2]);
    std::cout << f[n].ToString() << std::endl;
    return 0;
}
0
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35
29.06.2018, 16:12  [ТС]
Да библиотеки больших чисел у меня тоже есть. В коде котором я написал выше это упрощенная версия больших чисел, которая в каждой ячейке(элемент массива типа вектор) хранит только число не более чем из 9 цифр и умеет только складывать(для Фибоначчи больше не нужно). Полноценная библиотека будет обсчитывать число целиком, и на языке Perl у меня ушло 10 минут на это. На с++ мое решение работало дольше, и я не стал ждать результата и решил обсчитать только нужные мне 9 чисел.

Добавлено через 57 минут
Что-то я теряю при делении на 10 и не знаю как это использовать, компенсировать.
0
475 / 427 / 290
Регистрация: 10.03.2015
Сообщений: 1,782
29.06.2018, 21:26
У тебя на 43 числе (70140873 701408733)
Почему-то теряется в "первых 9 цифрах" крайняя 3ка. Хотя цифр всего 9 там, а не больше, а в "последние 9" записывается нормально. Ну а дальше уже от этого начинает плясать всё
Миниатюры
Сложение чисел до определенного разряда  
0
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35
29.06.2018, 21:48  [ТС]
Теряется при делении на 10. Я работаю над новым кодом. Идея в том чтобы добавить еще одну ячейку еще для 9 цифр, и того 2 ячейки для первых уже 18 чисел. Я понимаю что они будут плясать пока я не пойму почему а в этом случае пляска по идее не достанет первую ячейку еще очень долго.

Ну а вообще уже не стало для меня секретом что я решаю 104 задачу проекта Эйлера) Я нашел решение на с++ но я не смог вникнуть в суть его работы, особенно как-он складывает и решил переписать эту часть сам, но моих мозгов недостаточно... Прилагаю готовый код.

Кликните здесь для просмотра всего текста

// ////////////////////////////////////////////////////////
// # Title
// Pandigital Fibonacci ends
//
// # URL
// https://projecteuler.net/problem=104
// http://euler.stephan-brumme.com/104/
//
// # Problem
// The Fibonacci sequence is defined by the recurrence relation:
//
// `F_n = F_{n-1} + F_{n-2}`, where `F_1 = 1` and `F_2 = 1`.
//
// It turns out that `F_541`, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order).
// And `F_2749`, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital.
//
// Given that `F_k` is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find `k`.
//
// # Solved by
// Stephan Brumme
// May 2017
//
// # Algorithm
// My solution is based on a stripped down version of my ''BigNum'' class and stores 9 digits per cell, that's why it's called ''BillionNum'' (because ''MaxDigit = 1000000000'' ==> `10^9`).
// It only supports ''operator+=''.
//
// ''isPandigital(x, digits)'' returns true if ''x'' is ''1..digits''-pandigital, e.g. ''isPandigital(312, 3) == true'' because 312 is 3-pandigital.
// The original problem assumes ''digits = 9''.
// ''x'' 's digits are chopped off step-by-step and a bitmask tracks which digits we have already seen.
// Zero is not part of any pandigital number, not even implicit leading zeros.
//
// The ''main'' routines analyzes the lower digits first.
// Only when they are pandigital then the highest digits are checked, too, because that's bit slower:
// I take all digits from the highest cell of my ''BillionNum''. If there are too few digits, all digits in its neighboring cell are included.
// We might have too many digits now, therefore I remove the lowest digit until the number of digits is correct.
// If these digits are pandigital, then we are done.
//
// Finding the next Fibonacci number involves ''operator+='' of ''BillionNum''. The default algorithm is:
// `F_{next} = F_a + F_b`
// `F_a = F_b`
// `F_b = F_{next}`
// ==> quite a few memory allocations, and many object constructor/destruction will take place behind the curtain.
// A simple trick to improve performance is to use these equations instead, which get rid of these "memory/object bookkeeping" effects:
// `F_a += F_b` (add in-place)
// `F_a <=> F_b` (swap contents of both object, which is technically just swapping two pointers)
//
// The main performance boost comes from my next trick:
// - we check the lowest digit whether they are pandigital
// - we check the highest digit whether they are pandigital
// - __but we don't care what the other digits are__
// ==> whenever a number exceeds a certain size, I delete digits from the middle
// Currently I delete if there are more than 10 cells, which represent `9 x 10 = 90` digits.
// There is no special reason why I chose 10, it was the first number that I tried and it worked immediately.
// The solution is found 100x faster now ...
//
// # Alternatives
// I saw some people used clever `log` arithmetic to find the highest digits.
// This works for the original Fibonacci numbers but not the generalized Fibonacci numbers of the Hackerrank problem.
//
// # Hackerrank
// The user can define `F_1` and `F_2` as well as how many digits should be pandigital.


C++
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
#include <iostream>
#include <vector>
 
//#define ORIGINAL
 
// store single digits with lowest digits first
// e.g. 1024 is stored as { 4,2,0,1 }
struct BillionNum : public std::vector<unsigned int>
{
  // must store exactly 9 digits per cell
  static const unsigned int MaxDigit = 1000000000;
 
  // fill one cell
  BillionNum(unsigned int x)
  {
    push_back(x);
  }
 
  // add a big number
  void operator+=(const BillionNum& other)
  {
    // this code is a 95% copy of my BigNum class
 
    // add in-place, make sure it's big enough
    if (size() < other.size())
      resize(other.size(), 0);
 
    unsigned int carry = 0;
    for (size_t i = 0; i < size(); i++)
    {
      // perform standard addition algorithm
      carry += operator[](i);
      if (i < other.size())
        carry += other[i];
      else
        if (carry == 0)
          return;
 
      if (carry < MaxDigit)
      {
        // no overflow
        operator[](i) = carry;
        carry         = 0;
      }
      else
      {
        // yes, we have an overflow
        operator[](i) = carry - MaxDigit;
        carry         = 1;
      }
    }
 
    if (carry > 0)
      push_back(carry);
  }
};
 
// return true if x is pandigital (1..digits)
bool isPandigital(unsigned int x, unsigned int digits = 9)
{
  unsigned int mask = 0; // zero is not allowed, only 1 to 9
  for (unsigned int i = 0; i < digits; i++)
  {
    // get next digit
    auto current = x % 10;
    if (current == 0 || current > digits)
      return false;
 
    auto bit = 1 << current;
    // already seen ?
    if ((mask & bit) != 0)
      return false;
 
    // mark that digit as "used"
    mask |= bit;
    x    /= 10;
  }
 
  return true;
}
 
int main()
{
  unsigned int first  = 1; // F_1 = 1
  unsigned int second = 1; // F_2 = 1
  unsigned int digits = 9; // 9-pandigital (1..9)
 
#ifndef ORIGINAL
  std::cin >> first >> second >> digits;
#endif
 
  if (first == 1 && digits == 1)
  {
    std::cout << "1" << std::endl;
    return 0;
  }
 
  unsigned long long Modulo = 1; // 10^digits
  for (unsigned i = 1; i <= digits; i++)
    Modulo *= 10;
 
  // convert to a simplified BigNum
  BillionNum a = first;
  BillionNum b = second;
 
  for (unsigned int i = 2; i <= 2000000; i++)
  {
    // analyze the lowest digits
    auto lowest = b.front() % Modulo;
    bool isPanLow = isPandigital(lowest, digits);
 
    // look at the highest digits
    if (isPanLow)
    {
      unsigned long long highest = b.back();
      // maybe too few digits: use next cells, too
      if (highest < Modulo && b.size() > 1)
        highest = highest * BillionNum::MaxDigit + b[b.size() - 2];
 
      // too many digits ? shrink until we have the right number of digits
      while (highest >= Modulo)
        highest /= 10;
 
      // check if pandigital
      if (isPandigital(highest, digits))
      {
        // yes, pandigital on both ends !
        std::cout << i << std::endl;
        return 0;
      }
    }
 
    // next Fibonacci number
    a += b;
    std::swap(a, b);
 
    // don't compute all digits:
    // - look at the lowest digits
    // - and look at the highest (incl. some of its neighbors because of carry)
    // => remove those in the middle
    // => my "magic numbers" 10 and 2 were chosen pretty much at random ...
    if (a.size() > 10)
    {
      a.erase(a.begin() + 2);
      b.erase(b.begin() + 2);
    }
  }
 
  // failed
  std::cout << "no solution" << std::endl;
  return 0;
}
Перегрузка оператора += структуры BillionNum для меня здесь вообще темный лес.
0
7438 / 5030 / 2892
Регистрация: 18.12.2017
Сообщений: 15,692
29.06.2018, 22:50
Вы бы ещё бином Ньютона применили держите код:

C++
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
#include <iostream>
using namespace std;
 
int main()
{
   unsigned long long int a=1, b=1, k;
   int n;
   string s;
 
   do
   {
   cout <<"n="; cin >>n;
   if (n<1 || n>90) cout <<"1<=n<=90, Repeat please...\n";
   }
   while (n<1 || n>90);
    
   cout <<1<<"\n"<<1<<"\n";
   for(int i = 1; i <= n; i++)
     {
     k=a+b;
     a=b;
     b=k;
     s = to_string(k);
     string s1(s, 0, 9);
     cout <<s1<<"\n";
     }  
system("pause");
return 0;
}
не совсем понял Вас насчёт сложения в заголовке темы
0
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35
30.06.2018, 00:10  [ТС]
Было бы все так просто) Вот только нужное мне число находиться на 329468 позиции и состоит из 68856 цифр) Видимо нам всем придется пока смириться что мы недостойны того парня который написал код который в моем предыдущем сообщении)

Добавлено через 47 минут
Я наконец-то изучил его код. Структура работает так же, как в библиотеке больших чисел, которая у меня уже была. Только он ее упростил. Научил делать только сложение и все. В каждой ячейке(элементе массива) храниться число из 9 цифр. Когда ячеек больше 10, то он рандомно удаляет из середины ячейку, чтобы не считать все число целиком и пляска которая была у меня - не возникает, однако она по-любому, как мне кажется в какой-то ячейке должна быть, но нужные нам ячейки(конец и начало) она не затрагивает. В общем это решение конечно лучше, чем в первом моей сообщении, мне оно кажется более правильным) Но в моем решении из первого сообщения ограничить количество разрядов до 15(что я и сделал ранее) то эта пляска тоже меня не достигает. А искать алгоритм чтобы пляски не было это видимо сложнее, чем сама задача) Если я все верно понял, из того что написал то мое решение на 15% быстрей.
0
0 / 0 / 0
Регистрация: 08.05.2012
Сообщений: 35
30.06.2018, 01:38  [ТС]
Кому интересно - прилагаю программу и исходник
Вложения
Тип файла: 7z 104-LLVM.7z (95.7 Кб, 6 просмотров)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
30.06.2018, 01:38
Помогаю со студенческими работами здесь

найти сумму цифр второго разряда всех чисел
дана непустая последовательность чисел.найти сумму цифр второго разряда всех чисел

Каждое из двух заданных чисел циклически сдвинуть влево на 2 разряда
Даны два числа (регистры B и С) каждое из них циклически сдвинуть влево на 2 разряда

Умножение чисел начиная с младших разряда множителей со сдвигом суммы частичных произведений вправо
Нужно создать программу: умножение чисел начиная с младших разряда множителей со сдвигом суммы частичных произведений вправо.Очень нужно....

Сколько существует шестизначных чисел, если первая цифра разряда может быть нулем, число кратно 4
Сколько существует шестизначных чисел, если первая цифра разряда может быть нулем, цифры не должны повторяться и число должно делиться на 4?

Дано два числа, если значения 5-го разряда в первом числе 0, изменить второе число на сумму этих чисел
Здраствуйте помогиет пожалуйста с заданием: Дано два числа, если значения 5-го розряда в первом числе 0, изменить второе число на сумму...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка. Рецензия / Мнение/ Перевод https:/ / **********/ gallery/ thinkpad-x220-tablet-porn-gzoEAjs . . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru