C++ program for converting decimal to binary - c++

I need to program a method that will pass two int numbers i1 and i2
and return the number that has more ones in its binary representation.

This thread should help you get the binary representations
C++ - Decimal to binary converting
later with your binary arrays you can use
#include <numeric>
std::accumulate(binaryArr, binaryArr + sizeof(binaryArr)/sizeof(binaryArr[0]), 0);
to count the number of ones.
Also this really looks like solve my homework for me type of question, try reaserching and solving the problem yourself, and then asking your question with some code samples. This way you actually learn

first of all you should find way to find how many ones contains number(count_ones_binary function), and then you just use this function to solve you problem
#include <iostream>
int count_ones_binary(int x)
{
int res = 0;
while (x != 0)
{
if (x % 2 != 0)
res++;
x /= 2;
}
return res;
}
void more_ones_binary(int i1, int i2)
{
int count_i1 = count_ones_binary(i1);
int count_i2 = count_ones_binary(i2);
if (count_i1 > count_i2)
std::cout << "i1 have more ones\n";
else if (count_i1 < count_i2)
std::cout << "i2 have more ones\n";
else std::cout << "equal\n";
}

Related

Bernoulli numbers with Boost are different from Mathematica

In the latest Boost, there is a function to compute the Bernoulli number, but I miss what it does exactly.
For example, Mathematica, Python mpmath and www.bernoulli.org say that:
BernoulliB[1] == -1/2
but the boost version
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/special_functions/bernoulli.hpp>
boost::multiprecision::cpp_dec_float_100 x = bernoulli_b2n<boost::multiprecision::cpp_dec_float_100>(1);
returns 0.166667
Why this difference? Am I missing something?
All odd Bernoulli numbers are zero, apart of B1, which you know is -1/2. So,
boost::math::bernoulli_b2n returns the only even (2nth) Bernoulli numbers.
For example, to get B4 you need to actually pass 2:
std::cout
<< std::setprecision(std::numeric_limits<double>::digits10)
<< boost::math::bernoulli_b2n<double>(2) << std::endl;
and if you pass 1, you get B2.
See docs: http://www.boost.org/doc/libs/1_56_0/libs/math/doc/html/math_toolkit/number_series/bernoulli_numbers.html
Of course, you can make a simple wrapper, to imitate preferred syntax1:
double bernoulli(int n)
{
if (n == 1) return -1.0 / 2.0; // one
if (n % 2) return 0; // odd
return boost::math::bernoulli_b2n<double>(n / 2);
}
int main()
{
std::cout << std::setprecision(std::numeric_limits<double>::digits10);
for (int i = 0; i < 10; ++i)
{
std::cout << "B" << i << "\t" << bernoulli(i) << "\n";
}
}
or even a class with overloaded operator[] (for demanding persons ;) ):
class Bernoulli
{
public:
double operator[](int n)
{
return bernoulli(n);
}
};
or even make use of template magic and do all this checks at compile time (I will left it as an exercise for a reader ;) ).
1Please note, that this exact function body is not well verified and can contains mistakes. But I hope you've got the idea of how you can make a wrapper.

Large factorial series

I have to print series :-
n*(n-1),n*(n-1)*(n-2),n*(n-1)*(n-2)*(n-3),n*(n-1)*(n-2)*(n-3)*(n-4)...,n!.
Problem is large value of n , it can go upto 37 and n! will obviously go out of bounds ?
I just cant get started , please help , how would you have tackled situation if you were in my place ?
It depends on the language you are using. Some languages automatically switch to a large integer package when numbers get too large for the machine's native integer representation. In other languages, just use a large integer library, which should handle 37! easily.
Wikipedia has a list of arbitrary-precision arithmetic libraries for some languages. There are also lots of other resources on the web.
3 year old problem looked fun.
Simple create a routine to "multiply" a string by a factor. Not highly efficient, yet gets the job done.
#include <stdlib.h>
#include <string.h>
void mult_array(char *x, unsigned factor) {
unsigned accumulator = 0;
size_t n = strlen(x);
size_t i = n;
while (i > 0) {
i--;
accumulator += (unsigned)(x[i]-'0')*factor;
x[i] = (char) (accumulator%10 + '0');
accumulator /= 10;
}
while (accumulator > 0) {
memmove(x+1, x, ++n);
x[i] = (char) (accumulator%10 + '0');
accumulator /= 10;
}
}
#include <stdio.h>
void AS_Factorial(unsigned n) {
char buf[1000]; // Right-size buffer (problem for another day)
sprintf(buf, "%u", n);
fputs(buf, stdout);
while (n>1) {
n--;
mult_array(buf, n);
printf(",%s", buf);
}
puts("");
}
Sample usage and output
int main(void) {
AS_Factorial(5);
AS_Factorial(37);
return 0;
}
5,20,60,120,120
37,1332,46620,1585080,52307640,1673844480,...,13763753091226345046315979581580902400000000
I have just tried BigInteger in Java and it works.
Working code for demonstration purpose:
import java.math.BigInteger;
public class Factorial {
public static int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37};
public static BigInteger computeFactorial(int n) {
if (n==0) {
return new BigInteger(String.valueOf(1));
} else {
return new BigInteger(String.valueOf(n)).multiply(computeFactorial(n-1));
}
}
public static String getPowers(int n){
BigInteger input = computeFactorial(n);
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < primes.length && input.intValue() != 1;) {
BigInteger[] result = input.divideAndRemainder(new BigInteger(String.valueOf(primes[i])));
if (result[1].intValue() == 0) {
input = input.divide(new BigInteger(String.valueOf(primes[i])));
count++;
if (input.intValue() == 1) {sb.append(primes[i] + "(" + count + ") ");}
} else {
if (count!=0)
sb.append(primes[i] + "(" + count + ") ");
count = 0;
i++;
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(getPowers(37));
}
}
Feel free to use it without worrying about copyright if you want.
Update: I didn't realize you were using C++ until now. In that case, you can give boost BigInteger a try.
You may use big integer, but however this still has some limitations, but even though, this datatype can handle a very large value. The value that the big integer can hold, ranges from
-9223372036854775808 to 9223372036854775807 for the signed big integer, and
0 to 18446744073709551615 for the unsigned big integer.
If you really plan to do some bigger value computation which is bigger than the big integer data type, why not try the GMP library?
As from what the site says, "GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface." - gmplib.org
You could implement your own big-integer type if it's not permitted to use any thirdparty libraries. You can do something like that:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const int base = 1000 * 1000 * 1000; // base value, should be the power of 10
const int lbase = 9; // lg(base)
void output_biginteger(vector<int>& a) {
cout << a.back();
for (int i = (int)a.size() - 2; i >= 0; --i)
cout << setw(lbase) << setfill('0') << a[i];
cout << endl;
}
void multiply_biginteger_by_integer(vector<int>& a, int b) {
int carry = 0;
for (int i = 0; i < (int)a.size(); ++i) {
long long cur = (long long)a[i] * b + carry;
carry = cur / base;
a[i] = cur % base;
}
if (carry > 0) {
a.push_back(carry);
}
}
int main() {
int n = 37; // input your n here
vector<int> current(1, n);
for (int i = n - 1; n >= 1; --n) {
multiply_biginteger_by_integer(current, i);
output_biginteger(current);
}
return 0;
}

Get the number of digits in an int

How do I detect the length of an integer? In case I had le: int test(234567545);
How do I know how long the int is? Like telling me there is 9 numbers inside it???
*I have tried:**
char buffer_length[100];
// assign directly to a string.
sprintf(buffer_length, "%d\n", 234567545);
string sf = buffer_length;
cout <<sf.length()-1 << endl;
But there must be a simpler way of doing it or more clean...
How about division:
int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;
or use the log10 method from <math.h>.
Note that log10 returns a double, so you'll have to adjust the result.
Make a function :
int count_numbers ( int num) {
int count =0;
while (num !=0) {
count++;
num/=10;
}
return count;
}
Nobody seems to have mentioned converting it to a string, and then getting the length. Not the most performant, but it definitely does it in one line of code :)
int num = -123456;
int len = to_string(abs(num)).length();
cout << "LENGTH of " << num << " is " << len << endl;
// prints "LENGTH of 123456 is 6"
You can use stringstream for this as shown below
stringstream ss;
int i = 234567545;
ss << i;
cout << ss.str().size() << endl;
if "i" is the integer, then
int len ;
char buf[33] ;
itoa (i, buf, 10) ; // or maybe 16 if you want base-16 ?
len = strlen(buf) ;
if(i < 0)
len-- ; // maybe if you don't want to include "-" in length ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i=2384995;
char buf[100];
itoa(i, buf, 10); // 10 is the base decimal
printf("Lenght: %d\n", strlen(buf));
return 0;
}
Beware that itoa is not a standard function, even if it is supported by many compilers.
len=1+floor(log10(n));//c++ code lib (cmath)
looking across the internet it's common to make the mistake of initializing the counter variable to 0 and then entering a pre-condition loop testing for as long as the count does not equal 0. a do-while loop is perfect to avoid this.
unsigned udc(unsigned u) //unsigned digit count
{
unsigned c = 0;
do
++c;
while ((u /= 10) != 0);
return c;
}
it's probably cheaper to test whether u is less than 10 to avoid the uneccessary division, increment, and cmp instructions for cases where u < 10.
but while on that subject, optimization, you could simply test u against constant powers of ten.
unsigned udc(unsigned u) //unsigned digit count
{
if (u < 10) return 1;
if (u < 100) return 2;
if (u < 1000) return 3;
//...
return 0; //number was not supported
}
which saves you 3 instructions per digit, but is less adaptable for different radixes inaddition to being not as attractive, and tedious to write by hand, in which case you'd rather write a routine to write the routine before inserting it into your program. because C only supports very finite numbers, 64bit,32bit,16bit,8bit, you could simply limit yourself to the maximum when generating the routine to benefit all sizes.
to account for negative numbers, you'd simply negate u if u < 0 before counting the number of digits. of course first making the routine support signed numbers.
if you know that u < 1000,
it's probably easier to just write, instead of writing the routine.
if (u > 99) len = 3;
else
if (u > 9) len = 2;
else len = 1;
Here are a few different C++ implementations* of a function named digits() which takes a size_t as argument and returns its number of digits. If your number is negative, you are going to have to pass its absolute value to the function in order for it to work properly:
The While Loop
int digits(size_t i)
{
int count = 1;
while (i /= 10) {
count++;
}
return count;
}
The Exhaustive Optimization Technique
int digits(size_t i) {
if (i > 9999999999999999999ull) return 20;
if (i > 999999999999999999ull) return 19;
if (i > 99999999999999999ull) return 18;
if (i > 9999999999999999ull) return 17;
if (i > 999999999999999ull) return 16;
if (i > 99999999999999ull) return 15;
if (i > 9999999999999ull) return 14;
if (i > 999999999999ull) return 13;
if (i > 99999999999ull) return 12;
if (i > 9999999999ull) return 11;
if (i > 999999999ull) return 10;
if (i > 99999999ull) return 9;
if (i > 9999999ull) return 8;
if (i > 999999ull) return 7;
if (i > 99999ull) return 6;
if (i > 9999ull) return 5;
if (i > 999ull) return 4;
if (i > 99ull) return 3;
if (i > 9ull) return 2;
return 1;
}
The Recursive Way
int digits(size_t i) { return i < 10 ? 1 : 1 + digits(i / 10); }
Using snprintf() as a Character Counter
⚠ Requires #include <stdio.h> and may incur a significant performance penalty compared to other solutions. This method capitalizes on the fact that snprintf() counts the characters it discards when the buffer is full. Therefore, with the right arguments and format specifiers, we can force snprintf() to give us the number of digits of any size_t.
int digits(size_t i) { return snprintf (NULL, 0, "%llu", i); }
The Logarithmic Way
⚠ Requires #include <cmath> and is unreliable for unsigned integers with more than 14 digits.
// WARNING! There is a silent implicit conversion precision loss that happens
// when we pass a large int to log10() which expects a double as argument.
int digits(size_t i) { return !i? 1 : 1 + log10(i); }
Driver Program
You can use this program to test any function that takes a size_t as argument and returns its number of digits. Just replace the definition of the function digits() in the following code:
#include <iostream>
#include <stdio.h>
#include <cmath>
using std::cout;
// REPLACE this function definition with the one you want to test.
int digits(size_t i)
{
int count = 1;
while (i /= 10) {
count++;
}
return count;
}
// driver code
int main ()
{
const int max = digits(-1ull);
size_t i = 0;
int d;
do {
d = digits(i);
cout << i << " has " << d << " digits." << '\n';
i = d < max ? (!i ? 9 : 10 * i - 1) : -1;
cout << i << " has " << digits(i) << " digits." << '\n';
} while (++i);
}
* Everything was tested on a Windows 10 (64-bit) machine using GCC 12.2.0 in Visual Studio Code .
As long as you are mixing C stdio and C++ iostream, you can use the snprintf NULL 0 trick to get the number of digits in the integer representation of the number. Specifically, per man 3 printf If the string exceeds the size parameter provided and is truncated snprintf() will return
... the number of characters (excluding the terminating null byte)
which would have been written to the final string if enough space
had been available.
This allows snprintf() to be called with the str parameter NULL and the size parameter 0, e.g.
int ndigits = snprintf (NULL, 0, "%d", 234567545)
In your case where you simply wish to output the number of digits required for the representation, you can simply output the return, e.g.
#include <iostream>
#include <cstdio>
int main() {
std::cout << "234567545 is " << snprintf (NULL, 0, "%d", 234567545) <<
" characters\n";
}
Example Use/Output
$ ./bin/snprintf_trick
234567545 is 9 characters
note: the downside to using the snprintf() trick is that you must provide the conversion specifier which will limit the number of digits representable. E.g "%d" will limit to int values while "%lld" would allow space for long long values. The C++ approach using std::stringstream while still limited to numeric conversion using the << operator handles the different integer types without manually specifying the conversion. Something to consider.
second note: you shouldn't dangle the "\n" of the end of your sprintf() conversion. Add the new line as part of your output and you don't have to subtract 1 from the length...

c++ stringstream is too slow, how to speed up? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Fastest way to read numerical values from text file in C++ (double in this case)
#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
#include <limits>
using namespace std;
static const double NAN_D = numeric_limits<double>::quiet_NaN();
void die(const char *msg, const char *info)
{
cerr << "** error: " << msg << " \"" << info << '\"';
exit(1);
}
double str2dou1(const string &str)
{
if (str.empty() || str[0]=='?') return NAN_D;
const char *c_str = str.c_str();
char *err;
double x = strtod(c_str, &err);
if (*err != 0) die("unrecognized numeric data", c_str);
return x;
}
static istringstream string_to_type_stream;
double str2dou2(const string &str)
{
if (str.empty() || str[0]=='?') return NAN_D;
string_to_type_stream.clear();
string_to_type_stream.str(str);
double x = 0.0;
if ((string_to_type_stream >> x).fail())
die("unrecognized numeric data", str.c_str());
return x;
}
int main()
{
string str("12345.6789");
clock_t tStart, tEnd;
cout << "strtod: ";
tStart=clock();
for (int i=0; i<1000000; ++i)
double x = str2dou1(str);
tEnd=clock();
cout << tEnd-tStart << endl;
cout << "sstream: ";
tStart=clock();
for (int i=0; i<1000000; ++i)
double x = str2dou2(str);
tEnd=clock();
cout << tEnd-tStart << endl;
return 0;
}
strtod: 405
sstream: 1389
update: remove undersocres, env: win7+vc10
C/C++ text to number formatting is very slow. Streams are horribly slow but even C number parsing is slow because it's quite difficult to get it correct down to the last precision bit.
In a production application where reading speed was important and where data was known to have at most three decimal digits and no scientific notation I got a vast improvement by hand-coding a floating parsing function handling only sign, integer part and any number of decimals (by "vast" I mean 10x faster compared to strtod).
If you don't need exponent and the precision of this function is enough this is the code of a parser similar to the one I wrote back then. On my PC it's now 6.8 times faster than strtod and 22.6 times faster than sstream.
double parseFloat(const std::string& input)
{
const char *p = input.c_str();
if (!*p || *p == '?')
return NAN_D;
int s = 1;
while (*p == ' ') p++;
if (*p == '-') {
s = -1; p++;
}
double acc = 0;
while (*p >= '0' && *p <= '9')
acc = acc * 10 + *p++ - '0';
if (*p == '.') {
double k = 0.1;
p++;
while (*p >= '0' && *p <= '9') {
acc += (*p++ - '0') * k;
k *= 0.1;
}
}
if (*p) die("Invalid numeric format");
return s * acc;
}
string stream is slow. Quite very slow. If you are writing anything performance critical that acts on large data sets ( say loading assets after a level change during a game ) do not use string streams. I recommend using the old school c library parsing functions for performance, although I cannot say how they compare to something like boost spirit.
However, compared to c library functions, string streams are very elegant, readable and reliable so if what you are doing is not performance ciritcal I recommend sticking to streams.
In general, if you need speed, consider this library:
http://www.fastformat.org/
(I'm not sure if it contains functions for converting strings or streams to other types, though, so it may not answer your current example).
For the record, please note you're comparing apples to oranges here. strtod() is a simple function that has a single purpose (converting strings to double), while stringstream is a much more complex formatting mechanism, which is far from being optimized to that specific purpose. A fairer comparison would be comparing stringstream to the sprintf/sscanf line of functions, which would be slower than strtod() but still faster than stringstream. I'm not exactly sure what makes stringstream's design slower than sprintf/sscanf, but it seems like that's the case.
Have you considered using lexical_cast from boost?
http://www.boost.org/doc/libs/1_46_1/libs/conversion/lexical_cast.htm
Edit: btw, the clear() should be redundant.

How would I convert decimal into binary?

All I really know is PHP and I used the decbin function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?
A simple function could be defined such as this:
void binary(int decimal) {
int remainder;
if(decimal <= 1) {
std::cout << decimal;
return;
}
remainder = decimal % 2;
binary(decimal >> 1);
std::cout << remainder;
}
Although there are many other resources on the web on how to do this..
A noteworthy question for efficiency of it here, as you may want more than just that:
Efficiently convert between Hex, Binary, and Decimal in C/C++
you can do this non-recursively using something like this:
std::string Dec2Bin(int nValue, bool bReverse = false)
{
std::string sBin;
while(nValue != 0)
{
sBin += (nValue & 1) ? '1' : '0';
nValue >>= 1;
}
if(!bReverse)
std::reverse(sBin.begin(),sBin.end());
return sBin;
}
of course this isn't too architucture friendly, but it avoids cout, just incase your not using a console. it also outputs in any bit ordering.
You can use itoa if it's available on your compiler. Just remember it's not standard and if you need a standard method you're better off using the other solutions posted.
If you want to print it, just use this code here. If you want to return a string, instead of using cout, append to a C++ string instead.
offering the iterative approach (pardon the #defines (but i'm quite sure they will be compiled to the expression's value), i don't quite remember predefined macro/constants in C):
#define INT_ARCH 32
#define ARCH_SHIFTABLE (INT_ARCH - 1)
#define ARCH_MAX_INT 1 << ARCH_SHIFTABLE
void dec_to_bin(int decimal)
{
int shifter = ARCH_MAX_INT;
for(; shifter > 0; shifter >>= 1)
cout << (decimal & shifter);
}
Similar to #Necrolis answer without the need for an if, and the reversal of the string.
string decimalToBinary(int decimal) {
string binary;
while(decimal) {
binary.insert(0, 1, (decimal & 1) + '0');
decimal >>= 1;
}
return binary;
}
Do with simple way in c++
#include <iostream>
using namespace std;
int main()
{
long n, rem, binary=0, i=1;
cout<<"Enter a int: ";
cin>>n;
while(n != 0)
{
rem = n%2;
n = n/2;
binary= binary + (rem*i);
i = i*10;
}
cout<< "\nAns: "<<binary <<endl;
return 0;
}