简体   繁体   English

如何找出一个数字是否在斐波那契数列中

[英]How to find out if a number is in the Fibonacci Sequence

I have created a function that gives the Fibonacci number for a given input.我创建了一个 function,它给出了给定输入的斐波那契数。 I now want to create a function to check if a given number is in the Fibonacci Sequence.我现在想创建一个 function 来检查给定的数字是否在斐波那契数列中。

Here is what I have done so far:这是我到目前为止所做的:

-- Basic Fib Function 
fib :: Int -> Int 
fib x =
  if x < 1
    then 0
    else if x < 2
           then 1
           else fib (x - 1) + fib (x - 2)

-- Outputs list of all the functions 
fibList :: [Int]
fibList  = map fib [1..]
--  function that takes an Integer, and returns True if the argument is a Fibonacci number and False otherwise
isFib :: Int -> [Int] -> Bool
isFib n fibList
    |n `elem` fibList = True
    |otherwise = False

fibList works but the computation is taking very long time. fibList有效,但计算需要很长时间。 Also, I have done this:另外,我已经这样做了:

fibList' :: [Int]
fibList'  = map fib [1..100]

isFib' :: Int -> [Int] -> Bool
isFib' n fibList'
    |n `elem` fibList' = True
    |otherwise = False

With a smaller number, it still takes a long time to compute数字较小,计算时间仍然很长

ghci ghci

The problem is that n is an Int and fibList is an [Int] , you can not check if an Int and [Int] are the same, since these have a different type.问题是nInt并且fibList[Int] ,您无法检查Int[Int]是否相同,因为它们具有不同的类型。

Using elem will also fail in case the given number is not a Fibonacci number, since Haskell will keep enumerating over the list looking for the next candidate and will only return False if it reaches the end of the list, but if you generate an infinite list , then this will never end.如果给定的数字不是斐波那契数,使用elem也会失败,因为 Haskell 将继续枚举列表以寻找下一个候选者,并且只有在到达列表末尾时才会返回False ,但如果您生成无限列表,那么这将永远不会结束。

You can implement the isFib function where we check if the first item of the list is greater than n .您可以实现isFib function ,我们检查列表的第一项是否大于n If that is the case, we know that all remaining elements will be larger, and thus we can stop searching:如果是这样,我们知道所有剩余的元素都会更大,因此我们可以停止搜索:

isFib :: Int -> [Int] -> Bool
isFib _ [] = False
isFib n (x:xs)
    | x >= n = -- ...  🖘 to implement
    | otherwise = isFib n xs

where I leave filling in the part as an exercise.作为练习,我将填写部分。

Your fib function is not very efficient: it will take exponential time to determine the n -th element.您的fib function 效率不高:确定第n个元素需要指数时间 You can generate the list of Fibonacci numbers with:您可以使用以下命令生成斐波那契数列:

fibList :: [Int]
fibList = 0 : 1 : next fibList
  where next (f1 : fs@(f2:_)) = (f1+f2) : next fs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM