Fibonacci Sequence with unordered map in C++ [duplicate] - c++

I want to print the first 100 numbers in the fibonacci sequence. My program prints until around 20 numbers than the numbers turn negative.
Can someone explain this to me please and provide a fix?
Thanks,
/*Fibonacci sequence*/
#include <iostream>
using namespace std;
int main(){
long int i, fib;
int firstNum=0, secondNum=1;
cout << firstNum << endl;
cout << secondNum << endl;
for (i=0; i < 100; i++){
fib = firstNum + secondNum;
firstNum = secondNum;
secondNum = fib;
cout << fib << endl;
}
return 0;
}

What you are seeing is an integer overflow problem. firstNum and secondNum are not long.
This should fix it
unsigned long long i, fib;
unsigned long long firstNum=0, secondNum=1;
EDIT:
This will help you avoid overflow after the 20th number, but your program will still overflow. You can use unsigned long long, and you'll make it to the 100th sequence element.

Well even unsigned long long int throws out of range for higher fabonacci num(above 92) but if still interested you could store them digit by digit in array
see this
https://docs.google.com/file/d/0BwtP9e5j1RbpSjhvSG4wbkhGcmM/edit

Either We can store the values in dynamically created structures such
as Linked list (If we want to store all the Fibonacci numbers) OR
We can use just three string arrays to hold the sum and temp values to print it for this purpose which will solve your issue.
Please see this for reference
Print nth Fibonacci number [upto 1000 digits]

Related

C++ series summation code giving different answers on large input

I am adding numbers from 1 to n in C++. I have used both the iteration method and mathematical formula. The code works fine for up to 9 digits.
But when I give input a 10 digit number, the formula and iteration methods give separate answers.
I have tried to look it up on google but couldn't find any solution for this. My code:
#include <bits/stdc++.h>
using namespace std;
int main(){
unsigned long long i, n, sum = 0, out_put;
cout << "Sum of numbers from 1 to: ";
cin >> n;
/// using mathematical formula
out_put = n*(n+1);
out_put = out_put/2;
cout << " = " << out_put << endl;
/// using iteration
for (i=1; i<=n; i++){
sum = sum+i;
}
cout << " == " << sum << endl;
return 0;
}
How do know which one is the correct one? If I assume the formula can't be wrong then why is the iteration method giving incorrect answer? I have used unsigned long long to prevent overflow but still didn't work.
What you are seeing is overflow happening on your calculations at different points. 9,999,999,999 * 10,000,000,000 is ~9.9e19 while an unsigned long long holds ~1.8e19. So the result wraps around and you get one answer.
Your for loop is also going to overflow but it is going to do so at a different point meaning the answers will diverge from one another since the modulo arithmetic is happening with a smaller number.
Your problem is that n*(n+1) can be too large to store in an unsigned long long, even though the end result (half of that) which you calculate via iteration may still fit.
Assuming your unsigned long long has 64 bits, it can hold integers up to 18446744073709551615. Anything above that will restart from 0.
Edit: As Nathan points out, you can of course have both calculations overflow. The sum would still give the correct result modulo 2^64, but the direct calculation can be off because the division does not generally yield the same result modulo 2^64 after you have wrapped around.
#include <bits/stdc++.h>
using namespace std;
int main(){
unsigned long long i, n, sum = 0, out_put;
cout << "Sum of numbers from 1 to: ";
cin >> n;
/// using mathematical formula
out_put = n*(n+1);
out_put = out_put/2;
cout << " = " << out_put << endl;
/// using iteration
for (i=1; i<=n; i++){
sum = sum+i;
}
cout << " == " << sum << endl;
return 0;
}

Why doesn't the console output the right answer?

I have 2 numbers, n = 1000000000000, and j = 1. When I write
cout << n / j << endl;
The console outputs the right answer, 1000000000000.
However, when I do :
int d = n / j;
cout << d << endl;
The console outputs 3567587328.
Can someone please explain why this happens and what should I do?
The value you are using is greater than the maximum value that an integer variable can store.
If you need to perform arithmetic operation with such big numbers then you will have to use special classes that handle such numbers. Perhaps your implementation of C++ supports the long long data type?
The max int you can have is 2,147,483,647 which is way smaller that 10^12 that you have there, so you have an integer overflow. Instead of an int you could use long long.
Try using long.
long long d = n / j;
cout << d << endl;

Manually converting a char to an int - Strange behaviour

I've wrote a small program to convert a char to an int. The program reads in chars of the form '1234' and then outputs the int 1234:
#include <iostream>
using namespace std;
int main(){
cout << "Enter a number with as many digits as you like: ";
char digit_char = cin.get(); // Read in the first char
int number = digit_char - '0';
digit_char = cin.get(); // Read in the next number
while(digit_char != ' '){ // While there is another number
// Shift the number to the left one place, add new number
number = number * 10 + (digit_char - '0');
digit_char = cin.get(); // Read the next number
}
cout << "Number entered: " << number << endl;
return 0;
}
This works fine with small chars, but if I try a big char (length 11 and above) like 12345678901 the program returns the wrong result, -539222987.
What's going on?
12345678901 in binary is 34 bits. As a result, you overflowed the integer value and set the sign bit.
Type int is not wide enough to store such big numbers. Try to use unsigned long long int instead of the type int.
You can check what maximum number can be represented in the given integer type. For example
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<unsigned long long int>::max() << std::endl;
}
In C you can use constant ULLONG_MAX defined in header <limits.h>
Instead of using int, try to use unsigned long long int for your variable number.
That should solve your problem.
Overflowed integer. Use unsigned long long int.

C++ program to calculate the sum of all five-digit odd numbers?

I'm having a problem with the following simple code, I don't know why the output will become negative... The program is supposed to calculate the sum of all odd and five-digit numbers like 10001, 10003, 10005, etc.
#include <iostream>
using namespace std;
int main()
{
int num, sum = 0;
for (num = 10001 ; num <= 99999 ; num+=2){
sum += num;
}
cout << num << " " << sum;
return 0;
}
It means that there is an overflow of type int. That is this type can not represent the sum. I advice to declare variable sum like
long long int sum = 0;
After that you can compare the result with the maximum value stored in type int. For example
#include <limits>
//...
std::cout << std::numeric_limits<int>::max() << " " << sum << std::endl;;
Your int will likely overflow. Switch it to long
int num = 0;
long long sum = 0L;
Assuming you have a 4 byte int, the maximum value will be 2^31 - 1 == 2147483647. See this example
Your sum will come out to 2475000000 which will overflow.

Euler's number expansion

#include <iostream>
#include <iomanip>
using namespace std;
int a[8], e[8];
void term (int n)
{
a[0]=1;
for (int i=0; i<8; i++)
{
if (i<7)
{
a[i+1]+=(a[i]%n)*100000;
}
/* else
{
a[i+1]+=((a[i]/640)%(n/640))*100000;
}
*/
a[i]=a[i]/(n);
}
}
void sum ()
{
}
int factorial(int x, int result = 1)
{
if (x == 1)
return result;
else return factorial(x - 1, x * result);
}
int main()
{
int n=1;
for (int i=1; i<=30; i++)
{
term(n);
cout << a[0] << " "<< a[1] << " " << a[2] << " "
<< a[3] << " " << a[4] << " " << a[5]<< " "
<< " " << a[6] << " " << a[7] << endl;
n++;
for (int j=1; j<8; j++)
a[j]=0;
}
return 0;
}
That what I have above is the code that I have thus far.
the Sum and the rest are left purposely uncompleted because that is still in the building phase.
Now, I need to make an expansion of euler' number,
This is supposed to make you use series like x[n] in order to divide a result into multiple parts and use functions to calculate the results and such.
According to it,
I need to find the specific part of the Maclaurin's Expansion and calculate it.
So the X in e=1+x+(1/2!)*x and so on is always 1
Giving us e=1+1+1/2!+1/3!+1/n! to calculate
The program should calculate it in order of the N
so If N is 1 it will calculate only the corresponding factorial division part;
meaning that one part of the variable will hold the result of the calculation which will be x=1.00000000~ and the other will hold the actual sum up until now which is e=2.000000~
For N=2
x=1/2!, e=previous e+x
for N=3
x=1/3!, e=previous e+x
The maximum number of N is 29
each time the result is calculated, it needs to hold all the numbers after the dot into separate variables like x[1] x[2] x[3] until all the 30~35 digits of precision are filled with them.
so when printing out, in the case of N=2
x[0].x[1]x[2]x[3]~
should come out as
0.50000000000000000000
where x[0] should hold the value above the dot and x[1~3] would be holding the rest in 5 digits each.
Well yeah Sorry if my explanation sucks but This is what its asking.
All the arrays must be in Int and I cannot use others
And I cant use bigint as it defeats the purpose
The other problem I have is, while doing the operations, it goes well till the 7th.
Starting from the 8th and so on It wont continue without giving me negative numbers.
for N=8
It should be 00002480158730158730158730.
Instead I get 00002 48015 -19220 -41904 30331 53015 -19220
That is obviously due to int's limit and since at that part it does
1936000000%40320
in order to get a[3]'s value which then is 35200 which is then multiplied by 100000
giving us a 3520000000/40320, though the value of a[3] exceeds the limit of integer, any way to fix this?
I cannot use doubles or Bigints for this so if anyone has a workaround for this, it would be appreciated.
You cannot use floating point or bigint, but what about other compiler intrinsic integral types like long long, unsigned long long, etc.? To make it explicit you could use <stdint.h>'s int64_t and uint64_t (or <cstdint>'s std::int64_t and std::uint64_t, though this header is not officially standard yet but is supported on many compilers).
I don't know if this is of any use, but you can find the code I wrote to calculate Euler's number here: http://41j.com/blog/2011/10/program-for-calculating-e/
32bit int limits fact to 11!
so you have to store all the above facts divided by some number
12!/10000
13!/10000
when it does not fit anymore use 10000^2 and so on
when using the division result is just shifted to next four decimals ... (as i assumed was firstly intended)
of course you do not divide 1/n!
on integers that will be zero instead divide 10000
but that limits the n! to only 9999 so if you want more add zeroes everywhere and the result are decimals
also i think there can be some overflow so you should also carry on to upper digits