C++: How to properly print out the long long int using cout - c++

I wrote a code to get the factorial of a number in C++.
Here is the code.
#include <iostream>
using namespace std;
unsigned long long getFactorial(int);
int main(int argc, char **argv) {
int num = 5;
unsigned long long factorial = getFactorial(a);
cout << "Factorial of " << num << ": " << factorial << endl;
return 0;
}
unsigned long long getFactorial(int num) {
int i;
unsigned long long factorial = 1;
for(i=1; i<=num; i++) {
factorial *= i;
}
return factorial;
}
When I assign 5 to the num value, it properly prints out the right value, 120. But when I assign bigger numbers, for example 100, it simply prints out 0. How can I modify the code to properly print out the result on the console?

Now I found the answer by myself.
By using the gmp library, it became much easier to deal with the big integers.
Here's the modified code.
#include <iostream>
#include <gmpxx.h>
using namespace std;
mpz_class getFactorial(int);
int main(int argc, char **argv) {
int num = 100;
mpz_class factorial = getFactorial(num);
cout << "Factorial of " << num << ": " << factorial << endl;
return 0;
}
mpz_class getFactorial(int num) {
int i;
mpz_class factorial = 1;
for(i=1; i<=num; i++) {
factorial *= i;
}
return factorial;
}
In order to use the gmp library, I included the <gmpxx.h> header file. Next I changed the data type of the factorial variable and the return type of the getFactorial() function from unsigned long long to mpz_class which is the data type that represents the big integer.
After modifying the code, I compiled with GCC using the following flags.
$gcc test.cpp -lstdc++ -lgmpxx -lgmp -o test
The -lgmpxx and -lgmp flags are required to compile the code using the gmp library.
Now it works fine.

Related

C++ String to Number Custom function problem

I am trying to convert a string to number(long double) in C++. The problem arises when the number of digits after decimal point is greater than 3. It automatically rounds-off the to the nearest third digit after the decimal.
Additional info:
compiler: mingw
os: win10
Here's the code (test.cpp):
#include<iostream>
#include <string>
#include <math.h>
using namespace std;
double long c2n(string n) {
double long num=0;
bool isdec = false, is_ve=false;
// is_ve checks if number is negative
// isdec checks if the decimal point is reached and numbers can be added after decimal
char c;
// to store the the character which needs to be checked
short i = 0, count=1;
if (n.at(0)=='-')
{
i=1;
is_ve=true;
}
for (; i < n.length(); ++i)
{
c=n.at(i);
if (c=='.'){
isdec=true;
continue;
}
if (!isdec)
num=num*10+(c-'0');
else{
num = num + (c-'0')/pow(10,count);
count++;
}
}
if (is_ve)
{
return -num;
}
return num;
}
int main(int argc, char const *argv[])
{
cout << c2n("-912.301956") << endl;
return 0;
}
Here's the output:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302
What I discovered later:
if in the main function, we pass "-912.3016"
cout<< c2n("-912.3016") <<endl;
then output comes out to be:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302
but if we pass "-912.3015"
cout << c2n("-912.3015") <<endl;
then the o/p:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.301
Should I take double instead of long double or there is any other problem?
The default precision of std::cout is 6 as set by std::ios_base::init. So
auto val = 1234.56789;
std::cout<<val<<'\n`;
yields 1234.57 i.e. 6 digits (and rounds it accordingly). Set the precision accordingly using setprecision from the iomanip header and you should be able to see the correct value.
std::cout << std::setprecision(12) << c2n("-912.301956") << std::endl;

Segmentation Fault on Recursion

I want to count the number of recursivily call that has a number in the Collatz Sequence. But for such a bigger number for example 4565458458
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int f(int value){
if(value==1) return 1;
else if(value%2 == 0) return value/2;
else return 3*value+1;
}
int g(int value){
if(value == 0) return 0;
if (f(value)==1) return 1;
return 1 + g(f(value));
}
int main(int argc, char *argv[]){
int nSteps=0;
istringstream iss(argv[1]);
int;
if(!(iss >> num).fail()){
if(num < 0) cout << "0" << endl;
else{
nSteps = g(num);
cout << "Result: " << nSteps << endl;
}
}
else{
cout << "Incorrect line paramaters: ./g n" << endl;
}
return 0;
}
Your program will use a lot of stack-memory for large inputs.
In addition f should have the same input and output type (originally it had "unsigned long long" as input and int as output), or the result will be wrong.
I would advise you to first rewrite g without recursion, and if that works try to investigate how to get g to be efficient with tail-recursion (the current variant does probably not support it).
Using a debugger as others suggested is also good, especially if it crashes before calling 'g'.
Finally 'num<0' does not make sense for an unsigned 'num'.

Convert mpz_t to binary representation

I'm using mpz_t for big numbers. I need to convert the mpz_t to binary representation. I tried to use the mpz_export, but the returned array contains only 0s.
mpz_t test;
mpz_init(test);
string myString = "173065661579367924163593258659639227443747684437943794002725938880375168921999825584315046";
mpz_set_str(test,myString.c_str(),10);
int size = mpz_sizeinbase(test,2);
cout << "size is : "<< size<<endl;
byte *rop = new byte[size];
mpz_export(rop,NULL,1,sizeof(rop),1,0,test);
Using gmpxx (since it's taged as c++)
#include <iostream>
#include <gmpxx.h>
int main()
{
mpz_class a("123456789");
std::cout << a.get_str(2) << std::endl; //base 2 representation
}
There should be equivalent function in plain GMP
You have a minor error in your code: sizeof(rop) is either 4 or 8, depending on whether a pointer is 4 or 8 bytes on your system. You meant to pass simply size, not sizeof(rop).
Here's some code that works for me, with g++ -lgmp -lgmpxx:
#include <stdio.h>
#include <iostream>
#include <gmpxx.h>
int main()
{
mpz_class a("173065661579367924163593258659639227443747684437943794002725938880375168921999825584315046");
int size = mpz_sizeinbase(a.get_mpz_t(), 256);
std::cout << "size is : " << size << std::endl;
unsigned char *rop = new unsigned char[size];
mpz_export(rop, NULL, 1, 1, 1, 0, a.get_mpz_t());
for (size_t i = 0; i < size; ++i) {
printf("%02x", rop[i]);
}
std::cout << std::endl;
}

what is the exact time to run a program?

I want the exact time to run a program, I use it from clock(). But there is a problem that I can not give an exact time for small n like 2000.
I want it to return the correct answer for n=1000.
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
#define show_time(x, y) cout << endl << #x << " : " << y << endl;
int main()
{
int n;
cin >> n;
int *a = new int[n];
for(int i=0; i<n; i++)
a[i] = i;
random_shuffle(a, a+n);
int last = clock();
//STL_sort:
sort(a, a+n);
int lastP = clock();
show_time(STL_sort, (double)(lastP-last)/CLOCKS_PER_SEC);
return 0;
}
The output is 0. (Definitely 0 will not be the answer)
What platform are you running on? If you're on Windows, you could try the high-resolution time library.
If you have access to C++11, there is a header called chrono that has similar functionality, and is portable (ish)!

Print binary representation of a float number in C++ [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Float to binary in C++
I want to print out the binary representation of a float number in C++. Not very practical, just out of curiosity.
The following program doesn't compile though. The reinterpret_cast fails. What kind of cast can I use so that I can do the " &(1 << i) " part?
#include <iostream>
using namespace std;
void toBinary(float num) {
int numi = reinterpret_cast<int>(num);
cout << num << " " << numi << endl;
for (int i = 0; i < 8 * sizeof(num); i++){
if (numi & (1<<i)) {
cout << 1;
} else {
cout << 0;
}
}
cout << endl << endl;
}
int main() {
float a;
cout << sizeof(int) << " " << sizeof(float) << endl;
a = 13.5;
toBinary(a);
toBinary(13.9);
toBinary(2 * a);
toBinary(-a);
}
There's a much easier way. Take a pointer to the float, and reinterpret_cast it to a pointer to char. Now loop through sizeof(float) and convert each char to 8 binary digits. This method works for doubles too.
Use a union. I did this code to do exactly what you want:
// file floattobinary.cc
#include <string>
#include <inttypes.h> // for uint32_t
using namespace std;
void floatToBinary(float f, string& str)
{
union { float f; uint32_t i; } u;
u.f = f;
str.clear();
for (int i = 0; i < 32; i++)
{
if (u.i % 2) str.push_back('1');
else str.push_back('0');
u.i >>= 1;
}
// Reverse the string since now it's backwards
string temp(str.rbegin(), str.rend());
str = temp;
}
Below is a test program to run this function:
// file test.cc
#include <iostream>
#include <string>
#include <cstdlib> // for atof(3)
using namespace std;
void floatToBinary(float, string&);
int main(int argc, const char* argv[])
{
string str;
float f;
if (argc > 1)
{
f = static_cast<float>(atof(argv[1]));
floatToBinary(f, str);
}
cout << str << endl;
return 0;
}
Compile and run (I'm using GNU g++ on Linux):
me#mypc:~/college/c++/utils$ g++ -c floattobinary.cc
me#mypc:~/college/c++/utils$ g++ -c test.cc
me#mypc:~/college/c++/utils$ g++ -o test *.o
me#mypc:~/college/c++/utils$ ls
floattobinary.cc floattobinary.o test* test.cc test.o
me#mypc:~/college/c++/utils$ ./test 37.73
01000010000101101110101110000101
me#mypc:~/college/c++/utils$ ./test 2.0
01000000000000000000000000000000
me#mypc:~/college/c++/utils$ ./test 0.0
00000000000000000000000000000000
me#mypc:~/college/c++/utils$ ./test 237.74
01000011011011011011110101110001
me#mypc:~/college/c++/utils$ ./test 2.74e12
01010100000111110111110100101111
me#mypc:~/college/c++/utils$ ./test 2.74e13
01010101110001110101110001111010
me#mypc:~/college/c++/utils$ ./test -88.37
11000010101100001011110101110001