Problem with fibonacci function. C++ - c++

Should return the n place of the array. But instead of the value I'm only getting 0.
int fibonacci(int n)
{
int f[100];
f[0] = 0;
f[1] = 1;
for (int i=2; i<n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n];
}
int main()
{
cout << fibonacci(3);
return 0;
}
New CODE:
New problem its returning one number further then it should. For example if 'n==7' its returning '13' not '8' like it should.
int fibonacci(int n)
{
int f[100] = { 0, 1 };
for (int i=2; i<=n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n-1];
}
int main()
{
cout << fibonacci(7);
return 0;
}

well, you never set f[n], you only go up to i < n, that is, i == n-1.
try returning f[n-1]
EDIT: as Chris Lutz pointed out my answer is no good as it would give an invalid result if you called fibonacci(0)
Like many have answered already, the best solution is to loop until i <= n
Unless, of course, you want fibonacci(3) to return the 3rd element in the fibonacci sequence and not the 4th, in which case fibonacci(0) wouldn't really make sense, and the right return value would be f[n-1]... still the n==0 case should be handled somehow, as should the n<0and the n>100 cases.
you can return f[n-1] as long as you check for the right boundaries:
int fibonacci(int n)
{
int f[100] = { 0, 1 };
if ((n <= 0) || (n > 100))
return -1;//return some invalid number to tell the caller that he used bad input
for (int i=2; i < n; i++) // you can use i < n here
{
f[i] = f[i-2] + f[i-1];
}
return f[n-1];
}

Your loop termination condition is wrong. Since this is homework perhaps you can work out why.

You forgot to initialize the n-th value of the array. You return f[n] but only initialize up to n-1.

n is the index that is never reached in your version. You just need to replace the < with <= in your for loop conditional. (You never assigned f[n] because n was never reached by the loop and so you got back a default value.)
int fibonacci(int n)
{
int f[100];
f[0] = 0;
f[1] = 1;
for (int i=2; i<=n; i++)
{
f[i] = f[i-2] + f[i-1];
}
return f[n];
}
int main()
{
cout << fibonacci(3);
return 0;
}
And you don't need an array to perform the fib sequence by the way. Just use two variables and reassign them in the loop. Something like this:
int a = 0;
int b = 1;
for (int i=2; i<=n; i++)
{
b = a + b;
a = b;
}
return b;

The trouble is that you test for i < n (where n == 3 in your example call), but you return f[3] which has not been set to anything. You are 'lucky' that you're getting zeroes rather than random garbage.
Change the '<' to '<='.
Working Code #1
Retaining the full size array.
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f[100] = { 0, 1 };
if (n < 0 || n > 100)
return -1;
else if (n < 2)
return f[n];
for (int i = 2; i <= n; i++)
{
f[i] = f[i-2] + f[i-1];
//cout << "f[" << i << "] = " << f[i] << endl;
}
return f[n];
}
int main()
{
for (int i = 0; i < 8; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
Sample Output #1
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
Working Code #2
This uses an array of size 3, at the cost of a lot of modulo operations:
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f[3] = { 0, 1, 0 };
if (n < 0 || n > 100)
return -1;
else if (n < 2)
return f[n];
for (int i = 2; i <= n; i++)
{
f[i%3] = f[(i-2)%3] + f[(i-1)%3];
//cout << "f[" << i << "] = " << f[i%3] << endl;
}
return f[n%3];
}
int main()
{
for (int i = 0; i < 8; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
It produces the same output - so there is no point in repeating it.
Working Code #3
Avoiding arrays and modulo operations:
#include <iostream>
using namespace std;
static int fibonacci(int n)
{
int f0 = 0;
int f1 = 1;
if (n < 0 || n > 46)
return -1;
else if (n == 0)
return f0;
else if (n == 1)
return f1;
int fn;
for (int i = 2; i <= n; i++)
{
int fn = f0 + f1;
f0 = f1;
f1 = fn;
//cout << "f[" << i << "] = " << fn << endl;
}
return f1;
}
int main()
{
for (int i = -2; i < 50; i++)
cout << "fib(" << i << ") = " << fibonacci(i) << endl;
return 0;
}
The limit 46 is empirically determined as correct for 32-bit signed integers.
Example Output #3
fib(-2) = -1
fib(-1) = -1
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55
fib(11) = 89
fib(12) = 144
fib(13) = 233
fib(14) = 377
fib(15) = 610
fib(16) = 987
fib(17) = 1597
fib(18) = 2584
fib(19) = 4181
fib(20) = 6765
fib(21) = 10946
fib(22) = 17711
fib(23) = 28657
fib(24) = 46368
fib(25) = 75025
fib(26) = 121393
fib(27) = 196418
fib(28) = 317811
fib(29) = 514229
fib(30) = 832040
fib(31) = 1346269
fib(32) = 2178309
fib(33) = 3524578
fib(34) = 5702887
fib(35) = 9227465
fib(36) = 14930352
fib(37) = 24157817
fib(38) = 39088169
fib(39) = 63245986
fib(40) = 102334155
fib(41) = 165580141
fib(42) = 267914296
fib(43) = 433494437
fib(44) = 701408733
fib(45) = 1134903170
fib(46) = 1836311903
fib(47) = -1
fib(48) = -1
fib(49) = -1

With the call fibonacci(3), your for loop (inside the fibonacci function) goes until i < 3...
It means that the last assigment is f[2]. Not f[3] as expected (which is the value you return).

Don't you mean
return f[n-1];
I guess your compiler has set the array f[100] to 0?
Looks like the other guy has the right answer....

Related

Q - Given positive integers- m,n.. Find and print the values of 3^min(m,n) and 2^max(m,n)

Using C++ have written foloowing :
#include <iostream>
using namespace std;
int main()
{
int m,n;
int threemin, twomax;
threemin = 1; twomax = 1;
cout<<"Enter m"<<"Enter n";
cin>>m>>n;
int i,j;
for ((i = 1, j = 1) ; ( (i <= m), (j <= n) ) ; (i++,j++))
{
if (m>n){ i <= n ; threemin = threemin*3;} // for changing max value of i if m > n because we want to print 3^min(m,n)
else { threemin = threemin*3 ;} ; //
if (m>n){ j <= m ; twomax = twomax*2;} // same for changing j
else { twomax = twomax*2 ; }
}
cout<<"Threemax is"<<threemin<<"Twomax is"<<twomax;
return 0;
}
Issue -
For example m = 4 and n = 3 but here max(4,3) = 4 and min(4,3) = So, I have tried to such code which will give 3^min(m,n) and 2 ^max(4,3).
But Output comes out to be threemin = 3^3 = 81 and twomax = 2^3 = 8. Both are taking n as their exponent.
I am beginner .Kindly help me rectifying .
You can instead do something like this:
#include <iostream>
using namespace std;
int main()
{
int m, n, lesser, greater, threemin=1, twomax=1, i=1;
cout << "Enter m " << "Enter n";
cin >> m >> n;
lesser = min(m, n); // find smallest
greater = max(m, n); // find largest
while(i <= lesser) { // ride on smallest untill done
threemin *= 3;
twomax *= 2;
i++;
}
while(i <= greater) { // continue for largest
twomax *= 2;
i++;
}
cout << "Threemin is: " << threemin << ", Twomax is: " << twomax;
return 0;
}

generate random numbers in c ++ for small intervals

I'm working on a program to calculate the odds of a poker game, it's in process. I found how to generate random numbers but these random numbers depend on time and are not appropriate for generating random numbers in a small interval. I would like to know how I can generate random numbers without having to depend on computer time.
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
using namespace std;
int main() {
srand(time(NULL));
int N = 1000, T=100;
int j;
float tcouple = 0, ttrio = 0, tfull = 0, tpoker = 0, trien = 0;
struct Lettre{ int numero; char baton;};
Lettre lettre[5];
for(int a = 0; a < T; a++)
{
int couple = 0, trio = 0, full = 0, poker = 0;
for(int i = 0; i< N; i++){
int d = 0 ;
for(j = 0; j < 5; j++)
{
int r = 0;
lettre[j].numero = (1 + rand() % 13);
r = (1 + rand() % 4);
switch(r)
{
case 1:
lettre[j].baton = 'T';
break;
case 2:
lettre[j].baton = 'P';
break;
case 3:
lettre[j].baton = 'C';
break;
case 4:
lettre[j].baton = 'D';
break;
}
}
for(int l = 0; l < 4; l++)
{
for(int k = l + 1; k<5; k++)
{
if(lettre[l].numero == lettre[k].numero)
d = d + 1;
}
}
if (d == 1)
couple = couple + 1;
if (d == 3)
trio = trio + 1;
if(d == 4)
full = full + 1;
if(d==6)
poker = poker + 1;
}
tcouple = tcouple + couple;
ttrio = ttrio + trio;
tfull = tfull + full;
tpoker = tpoker + poker;
}
trien=(T*N)-(tcouple+ttrio+tfull+tpoker);
cout << "probabilite couple: " << tcouple/(T*N) <<endl;
cout << "probabilite trio: " << ttrio/(T*N) <<endl;
cout << "probabilite full: " << tfull/(T*N) <<endl;
cout << "probabilite poker: " << tpoker/(T*N) <<endl;
cout << "probabilite rien: " << trien/(T*N) << endl;
return 0;
}
You may want to keep a random numbers pool, which is filled at start or once a time period. It should be big enough so every time you get new random value from it it was a new one. In this case you may use uniform_int_distribution as Timo suggested or even rand.
struct RandPool
{
void Generate()
{
srand(time(nullptr));
for (int i = 0; i < 1000'000; ++i)
mNumbers.push_back(rand());
mIndex = 0;
}
int Next()
{
return mNumbers[mIndex++];
}
private:
int mIndex = 0;
std::vector<int> mNumbers;
};

Strange behaviour of pointers in C++

#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.

Finding 2 pentagonal numbers whose sum and difference produce pentagonal number

I am trying to calculate two pentagonal numbers whose sum and difference will produce another pentagonal number. In my main function I use pentagonal number theorem to produce pentagonal number sums that produce a pentagonal number and then I check if the difference of those 2 numbers is also pentagonal using is_pentagonal function.
I've written the following code in C++ and for some reason in doesn't give the correct answer and I'm not sure where the mistake is.
The thing is, when I get my answer d then j and k are not pentagonal. j and k simply go above the numerical limit and random numbers eventually produce pentagonal d and i don't get why it happens. Thank you.
bool is_perfect_square(int n)
{
if (n < 0) return false;
int root = sqrt(n);
return n == root * root;
}
bool is_pentagonal(int n)
{
if(is_perfect_square(24*n + 1) && (int)sqrt(24*n+1)%6 == 5)return true;
return false;
}
int main() {
int j = 0, k = 0, d = 0, n = 1;
while(!is_pentagonal(d))
{
j = (3*n+1)*(3*(3*n+1)-1)/2;
k = (n*(9*n+5)/2)*(3*n*(9*n+5)/2-1)/2;
d = k - j;
++n;
}
cout << d << endl;
return 0;
}
I've run this code in ideone:
#include <iostream>
#include <math.h>
using namespace std;
bool is_perfect_square(unsigned long long int n);
bool is_pentagonal(unsigned long long int n);
int main() {
// I was just verifying that your functions are correct
/*
for (int i=0; i<100; i++) {
cout << "Number " << i << " is pentagonal? " << is_pentagonal(i) << endl;
}
*/
unsigned long long int j = 0, k = 0, d = 0;
int n = 1;
while(!is_pentagonal(d))
{
j = (3*n+1)*(3*(3*n+1)-1)/2;
if (!is_pentagonal(j)) {
cout << "Number j = " << j << " is not pentagonal; n = " << n << endl;
}
k = (n*(9*n+5)/2)*(3 *n*(9*n+5)/2-1)/2;
if (!is_pentagonal(k)) {
cout << "Number k = " << k << " is not pentagonal; n = " << n << endl;
}
d = k - j;
++n;
}
cout << "D = |k-j| = " << d << endl;
return 0;
}
bool is_perfect_square(unsigned long long int n) {
if (n < 0)
return false;
unsigned long long int root = sqrt(n);
return n == root * root;
}
bool is_pentagonal(unsigned long long int n)
{
if(is_perfect_square(24*n + 1) && (1+(unsigned long long int)sqrt(24*n+1))%6 == 0)return true;
return false;
}
And the result is:
Number k = 18446744072645291725 is not pentagonal; n = 77
Number k = 18446744072702459675 is not pentagonal; n = 78
Number k = 18446744072761861113 is not pentagonal; n = 79
...
If you compare these numbers with 2^64 = 18 446 744 073 709 551 616 as reported at cplusplus.com you will notice you are very close to that. So basically what happens is that your algorithm is correct, but numbers quickly get so big they overflow, and then they are just wrong. See here to check what options you have now.

C++ generating a pascal triangle, wrong output

I have a problem with generating a pascal triangle in c++, same algorithm works good in java and in c++ it only works for the first two numbers of every line of the triangle in any other it generates way to big numbers. For example in java it generates:
1 5 10 10 5 1 and in C++: 1 5 1233124 1241241585 32523523500 etc
Here is code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int* tab;
int prev1;
int prev2;
public:
Pascal(int n) {
tab = new int[n+1];
prev1=0;
prev2=0;
for(int i = 0; i <= n; i++) {
for(int k = 0; k <= i; k++) {
if (k == 0) {
tab[k] = 1;
prev2 = 1;
} else {
prev1 = tab[k-1] + tab[k];
tab[k-1] = prev2;
prev2 = prev1;
}
}
}
}
int wspolczynnik(int m) {
return tab[m];
}
};
int main (int argc, char* argv[]) {
int n = 0, m = 0;
n = atoi(argv[1]); // konwersja string na int
if (n >= 0)
for (int i = 2; i < argc; i++) {
Pascal *wiersz = new Pascal(n);
m = atoi(argv[i]);
int result = wiersz->wspolczynnik(m);
if (m < 0 || m > n)
cout << m << " - element poza zakresem" << endl;
else
cout << m << " : " << result << endl;
delete[] wiersz;
}
return 0;
}
See if initializing the tab array helps:
tab = new int[n+1]();