I need help printing out large integers. I need to print a 64bit int with my pro
ID: 3871139 • Letter: I
Question
I need help printing out large integers. I need to print a 64bit int with my program, and I thought I had the code correct to do that. This works to print the lower fibonacci numbers, but the large ones are not working. Please take a look and tell me what you think. n in main is where you should be setting the fibonacci number. The long long's are all over the place because im trying to print out the 64 bit integers
#include
#include
#include
#include
#include
using namespace std;
void multiply(long long F[2][2], long long M[2][2]);
void power(int F[2][2], int n);
int fib(long long n)
{
int F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
void multiply(int F[2][2], int M[2][2])
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
void power(int F[2][2], int n)
{
int i;
int M[2][2] = {{1,1},{1,0}};
for (i = 2; i <= n; i++)
multiply(F, M);
}
int main()
{
long long n = 50;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
cout << n << " " << fib(n);
std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();
std::cout << "Time difference = " << std::chrono::duration_cast(end - begin).count() < getchar();
return 0;
}
Explanation / Answer
#include<iostream>
using namespace std;
void multiply(long long F[2][2], long long M[2][2]);
void power(long long F[2][2], long long n);
long long fib(long long n)
{
long long F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
void multiply(long long F[2][2], long long M[2][2])
{
long long x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
long long y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
long long z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
long long w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
void power(long long F[2][2], long long n)
{
long long i;
long long M[2][2] = {{1,1},{1,0}};
for (i = 2; i <= n; i++)
multiply(F, M);
}
int main()
{
long long n = 50;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
cout << n << " " << fib(n);
std::chrono::steady_clock::time_point end= std::chrono::steady_clock::now();
std::cout << "Time difference = " << std::chrono::duration_cast(end - begin).count() < getchar();
return 0;
}
============================================================
Now, it should work, I have added long long to all the data present, So it should work Now.
NOTE: Please Use your header files because I dont see your added header files
#include ?
Thanks, please let me know if it works for you or not
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.