【问题标题】:Integer overflow in Fibonacci number斐波那契数中的整数溢出
【发布时间】:2016-04-02 14:14:02
【问题描述】:

我正在解决这个关于斐波那契数列的 codechef 问题。它说数字是 1000 位,那么为什么它在扫描数组并将其存储在 unsigned long long int 中时不会导致测试人员的解决方案中的整数溢出。我不明白解决方案是如何工作的。以下是问题和测试人员的解决方案。

The Head Chef has been playing with Fibonacci numbers for long . He has learnt several tricks related to Fibonacci numbers . Now he wants to test his chefs in the skills . 

A fibonacci number is defined by the recurrence :

f(n) = f(n-1) + f(n-2) for n > 2 
and f(1) = 0 
and f(2) = 1 . 

Given a number A , determine if it is a fibonacci number.
Input

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains a single integer A denoting the number to be checked .
Output

For each test case, output a single line containing "YES" if the given number is a fibonacci number , otherwise output a single line containing "NO" .
Constraints

1 ≤ T ≤ 1000
1 ≤ number of digits in A ≤ 1000
The sum of number of digits in A in all test cases <= 10000.
Example

Input:
3
3
4
5

Output:
YES
NO
YES


**Tester's solution:**
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <cstring>
using namespace std;
int const mx = 6666;
set <unsigned long long> f;
unsigned long long fib[mx + 10];
char s[mx + 1];
int main(){
//  freopen("input.txt", "r", stdin);
//  freopen("output.txt", "w", stdout);
    fib[0] = 0;
    fib[1] = 1;
    f.insert(1);
    f.insert(0);
    int i;
    for (i = 2; i <= mx; i++){
        fib[i] = fib[i - 1] + fib[i - 2];
        f.insert(fib[i]);
    }
    int tc;
    cin>>tc;
    while (tc--){
        unsigned long long n = 0, ten = 10;
        cin>>s;
        int len = strlen(s);
        for (i = 0; i < len; i++){
            char q = s[i];
            unsigned long long a = q - '0';
            n = n * ten + a;
        }
        if (f.find(n) == f.end()) printf("NO\n");
        else printf("YES\n");
    }
    return 0;
} 

【问题讨论】:

    标签: fibonacci integer-overflow


    【解决方案1】:

    cplusplus你会看到,

    ULLONG_MAX unsigned long long int 类型的对象的最大值为 18446744073709551615 (264-1) 或更大。

    实际值取决于特定的系统和库实现,但应反映这些类型的限制 目标平台。

    以上信息只是为了让您知道它的一个大数字。此外,没有溢出的原因不是我提到的限制。

    judge 的输入文件很可能不包含任何可能导致溢出的输入。

    即使满足条件,仍然可以设置这样的输入,

    1 ≤ T ≤ 1000
    1 ≤ number of digits in A ≤ 1000
    The sum of number of digits in A in all test cases <= 10000.
    

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      相关资源
      最近更新 更多