Click here to Skip to main content
15,902,828 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C++
  1  #include<bits/stdc++.h>
  2  #define ull unsigned long long
  3  using namespace std;
  4  ull n;
  5  ull fib(ull n);
  6  int main(){
  7  	ios_base::sync_with_stdio(0);
  8  	cin.tie(0);
  9  	cin>>n;
 10  	cout<<fib(n)<<'\n';
 11  	return 0;
 12  }//1 1 2 3 5   8 13 21 34 55
 13  vector<ull> dp(n+1,0);
 14  ull fib(ull n){
 15  	if(dp[n]!=0) return dp[n];
 16  	if(n<=2) return 1;
 17  	return dp[n]=fib(n-1)+fib(n-2);
 18  }


What I have tried:

what is problem my code ?
i am writing fibonacci.
Posted
Updated 17-May-23 9:20am
v5

The first comment is that the code does not do what it probably should do. You write that you are doing Fibonacci, but not exactly what result you expect and what the error is.

Here are a few more comments:
The header <bits stdc++.h=""> is not a standard C++ header, surely <vector> would make more sense here.

Surely you have heard that global variables should be avoided. Unfortunately you have some of them, which are useless:
C++
ull n;
vector<ull> dp(n + 1, 0);

You use the functions sync_with_stdio() and cin.tie() for no apparent reason. I may be wrong, but I think they are superfluous here.

Using your own datatype when using a std::vector has the problem that it only supports max size_t.
Instead of accessing with the array notation, using the at() method would be safer, since an out_of_range exception would be thrown in case of an invalid index range.

From the comment I assume that the output of a row should look like this:
//1 1 2 3 5 8 13 21 34 55


Also, there seems to be an attempt in the code to find a recursive solution.

Remark: When it comes to calculating Fibonacci numbers efficiently, an iterative solution would be preferable to a recursive one. A recursive approach here is less efficient than an iterative solution because it performs many redundant calculations. For large values of n, this can also lead to a significant slowdown.

A standard vector can also only be addressed with an index of at most size_t, declaring the index with the data type ull is not useful.

To avoid that numbers are calculated several times it could make sense to store already calculated Fibonacci numbers in a vector and access them when needed.

The operator << is not overloaded by default for the datatype unsigned long long, and a direct overloading can lead to an ambiguity. There is something to be said for not using the self-defined datatype in either a std::vector or an ostream.

No matter what you do, there would be some changes to be made here.

A suggestion is to declare the vector as follows:
C++
std::vector<ull> fibSeq;

Then the recursive function with the following signature:
C++
ull fib(size_t n, std::vector<ull>& fibSeq);

call in a loop up to n:
C++
{ for (size_t i = 1; i <= n; ++i) {
  cout << " " << fib(i, fibSeq);
}
 
Share this answer
 
v2
Comments
CPallini 17-May-23 3:33am    
5.
Try
C++
ull fib(vector<ull> & vm, ull u)
{
  if ( vm.size() <= u ) vm.resize(u+1, 0);
  if ( vm[u] == 0)
  {
    if (u<=2)
      vm[u] = 1;
    else
      vm[u] = fib(vm, u-1) + fib(vm, u-2);
  }
  return vm[u];
}
 
Share this answer
 
Comments
merano99 17-May-23 13:28pm    
It doesn't work that way for me. My compiler expects the data type size_t as index and does not handle larger data types. For the code to work cross-platform and correctly it is recommended to use size_t. If the data type for the index is larger than size_t, more memory is required and overflow problems can occur.
The calls vm.resize(u + 1, 0) and vm[u] generate the following warning with me: warning C4244: "Argument": conversion of "unsigned __int64" to "const unsigned int", possible data loss.
With a custom template, the solution works, so +5.
CPallini 18-May-23 2:24am    
Thank you.
If one compares the solutions of C-Pallini and the questioner, it is noticeable that the solution works in principle. The essential problem arises, because the vector was declared at an unfavorable place and besides can be brought only with resize on the correct size, if n is known. So it should look like this. The result is then calculated correctly.
C++
cin >> n;
dp.resize(n + 1, 0);
// cout << fib(n) << '\n';
for (ull i = 1; i <= n; ++i) 
  cout << fib(i) << " ";

Custom data types are usually declared with typedef not with define.
C++
// #define ull unsigned long long
typedef unsigned long long ull;

If the own data type ull should also be used as index, one could use a modified vector template.
C++
// myvector-Template for exotic datatypes
template <typename T, typename IndexType = ull>
class myvector {
public:
    T& operator[](IndexType index)
        { return data[static_cast<size_t>(index)]; }
    size_t size() const 
        { return data.size(); }
    void resize(IndexType new_size) 
        { data.resize(static_cast<size_t>(new_size)); }
    void resize(IndexType new_size, const T& value) 
        { data.resize(static_cast<size_t>(new_size), value); }
    void reserve(IndexType new_capacity) 
        { data.reserve(static_cast<size_t>(new_capacity)); }
private:
    std::vector<T> data;
};

If a good recursive solution is sought here, it should look like what C.Pallini or I suggested.
C++
// Solution see C.Pallini
ull fib(myvector<ull>& vm,  ull u);
 
Share this answer
 
v4
Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C++
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900