How to overcome negative integer outputs in infinite fibonacci series in c++? - c++

I tried making infinite fibonacci series in c++ but after few terms it is showing negative integers. Here's the code:
int main(){
long long int a{0};
long long int b{1};
long long int c{1};
cout<<a<<endl<<b<<endl;
while (true){
cout<<c<<endl;
a=b;
b=c;
c=a+b;
}
}
I guess its because of size limit of long long int, but is there any way I can print upto infinity like in python?

As others have mentioned, there is no standard type that has infinite precision. You will need to use a third-party library, or write your own class that has this functionality.
One such library that implements arbitrary precision integers is boost multiprecision.
Here is an implementation of computing the first 500 numbers:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main()
{
using Int = boost::multiprecision::cpp_int;
Int a{0};
Int b{1};
Int c{1};
std::cout << a << std::endl << b << std::endl;
for (int i = 0; i < 500; ++i)
{
std::cout<< c << std::endl;
a=b;
b=c;
c=a+b;
}
}
Live Example

Related

why in decimal to binary code it does not work properly when we enter numbers above 63?

i wrote a code that recives the numbers from the base ten and gives us the binary number.But for numbers above 64, it just doesn't work properly.and i don't know why.please help me.
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int c; int b,a[c];
cin>>b;
for(c=0;b>1;c++)
{
a[c]=b%2;
b=b/2;
}
cout<<b;
c--;
for(c;c>=0;c--){
cout<<a[c];
}
getch();
The problem resides here:
int c; int b,a[c];
You are defining a Variable Length Array (not standard, btw) of size c, but you have not given c a value, therefore, this is undefined behaviour (use of c before giving it a value). Since you are dealing with integers, you can do int a[32] though, which should allow your code to work.
Another method with strings:
std::string str;
while ( b != 0 ) {
str = std::to_string( b % 2 ) + str;
b /= 2;
}
std::cout << str;
A few things to note:
main requires a return type, and should be int main()
conio.h is not standard, and shouldn't be used
int a[c] is a variable length array (VLA), not standard, and shouldn't be used.
using namespace std is a bad idea.
The problem has been pointed out in other answers so I'm just going to give you an alternative solution.
You could also try using bitset if your intent is to convert to binary.
#include <bitset>
using namespace std;
bitset<32> bv;
bv = 65;
cout << "Binary value " << bv <<"\n";
bv = 195;
cout << "Binary value " << bv <<"\n";

Counting and getting highest number of digits after decimal

I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}

long long division wrong

I am working in a project and in a certain time I have this problem. I have two very large numbers and I want to divide them and get an integer/long long integer. This is what's happening:
Code
#include <iostream>
using namespace std;
int main(){
long long n,m;
cin >> n >> m;
cout << n/m << endl;
}
The inputs can be numbers until 100,000,000,000,000,000 so the division is performing wrong.
Output
#1 n: 76543210987654321 m: 7654321
#2 76543210987654321/7654321 = 1410312449
The right answer is 10,000,000,130 so I am wondering what is happening...
The correct result is neither 1410312449 nor 10000000130. It is equal to 10000000129
At least it is what the GCC shows at www.ideone.com. You can try it yourself.
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
std::cout << n / m << std::endl;
return 0;
}
It seems that you place the result of the operation in an object of type int. Consider the following code
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
int x;
x = n / m;
std::cout << n / m << std::endl;
std::cout << x << std::endl;
return 0;
}
The output is
10000000129
1410065537
It seems, that the result of division is truncated to 32-bit value (int).
Try to use explicit cast to long long via static_cast.
Also, it is interesting to know result of sizeof(long long) on your compiler.

C++: reading a string, converting to dynamic int array

I am writing a program that asks the user to type in a very large int (much larger than the type int can handle). When receive this int from the user, it is stored in a string. Then, I want to convert this string into an int array (I am using a dynamic int array). After compiling and running the program, I get values that don't make sense. The values of my int array seem to be random gibberish. I don't see why this is so - it doesn't look like my loops are out of bound in the converting process. Please help. The purpose of creating an int array is to then come up with ways to add, subtract, multiply, and compare very large int values. To make it clear what I am intending to do: say the user types in "12345". I want to store this string value into an int array that would have a length of 5, each element corresponding to the next number in the int.
largeIntegers.h
#ifndef H_largeIntegers
#define H_largeIntegers
#include <iostream>
#include <string>
class largeIntegers
{
private:
void readInteger();
// reads integer
public:
std::string s_integer;
int* integer;
int length;
largeIntegers();
// default constructor
void outputInteger();
// outputs integer
};
#endif
largeIntegers.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
largeIntegers::largeIntegers()
{
readInteger();
}
void largeIntegers::readInteger()
{
int i = 0,j = 0, k;
cout << "Enter large integer: ";
cin >> s_integer;
for (; s_integer[i] != '\0'; i++);
length = i;
int* integer = new int[i];
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = s_integer[k++] - 48;
}
void largeIntegers::outputInteger()
{
for (int i = length - 1; i >= 0; i--)
cout << integer[i];
}
User.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
int main()
{
largeIntegers a;
cout << a.length << endl << endl;
cout << a.integer[0] << endl << a.integer[1] << endl;
a.outputInteger();
cout << endl << endl;
return 0;
}
I intentionally made the variables in the header public for debugging purposes. My output on the console after compiling is:
Enter large integer: 111
3
952402760
1096565083
10966961571096565083952402760
This is the problem
int* integer = new int[i];
change to
integer = new int[i];
Your version declares a local variable that just happens to have the same name as your class variable. Easy mistake to make.
also, using standards facilities like std::vector and std::getline would make your code much cleaner in addition to avoid the problem you had, and resolve memory leaks you have now if you call readInterger twice:
void largeIntegers::readInteger()
{
cout << "Enter large integer: ";
std::getline(std::cin, s_integer);
integer = std::vector(s_integer.size());
//your last loop to fill the array probably can be replaced by std::transform
}

Calculation not outputting expected answer

I'm trying to work out the arctan of a number using the formula:
arctan(x) = x - x^3/3 + x^5/5 - x^7/7...
I have to calculate it to 20 decimal places. The answer should be 0.78539....
This is the code I have written, including some debugging statements. The problem is in the calculation I think but I just can't see it. Could someone point me in the right direction please?
EDIT : Can't use the atan function, has to be manually calculated using a double variable from user input.
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double x;
int i;
int j;
int y=3;
cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
cin>>x;
//Calculate arctan of this number
cout<<x;
cout<<"\n";
cout<<y;
cout<<"\n";
cout<<"Start\n";
x=x-(pow(x,y)/y);
y=y+2;
cout << setprecision (20) << x;
cout<<"=x before loop\n";
cout<<y;
cout<<"=y before loop\n";
for(i=0;i<9;i++)
{
x=x+(pow(x,y)/y);
cout<<x;
cout<<"=x1 in loop\n";
y=y+2;
cout<<y;
cout<<"=y1 in loop\n";
x-(pow(x,y)/y);
cout<<x;
cout<<"=x2 in loop\n";
y=y+2;
cout<<y;
cout<<"=y2 in loop\n";
}
return 0;
}
Well, your x is changing! You probably want to use a different variable to store the value computed so far and the argument to your function. That said, don't expect to precise outputs because all those computations involve rounding.
This line:
x-(pow(x,y)/y);
might have something to do with your problem.
I would strong advise you use the inbuilt atan function, it is more than likely been well optimised for you architecture, as well as being a standard function recognised by most C++ programmers.
#include <cmath>
#include <iostream>
int main()
{
double d;
std::cout << "enter number" << std::endl;
std::cin >> d;
std::cout << "atan of: " << d
<< " is " << std::atan(d)
<< std::endl;
return 0;
}
I agree with #Mystical. I don't think you're going to get 20 digits of precision out of a double. I think you need a long double (if that exists on your system) or, perhaps you need to implement your own big-num class...