Translation from binary into decimal numbers in C++ - c++

I tried to build a function that calculates a binary number stored in a string into a decimal number stored in a long long. I'm thinking that my code should work but it doesn't.
In this example for the binary number 101110111 the decimal number is 375. But my output is completely confusing.
Here is my code:
#include <string>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
int main() {
std::string stringNumber = "101110111";
const char *array = stringNumber.c_str();
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < strlen(array); i++) {
result += pow(array[strlen(array) - subtrahend] * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Here is the output:
1
99
9703
894439
93131255
9132339223
894974720087
76039722530902
8583669948348758
What I'm doing wrong here?

'1' != 1 as mentioned in the comments by #churill. '1' == 49. If you are on linux type man ascii in terminal to get the ascii table.
Try this, it is the same code. I just used the stringNumber directly instead of using const char* to it. And I subtracted '0' from the current index. '0' == 48, so if you subtract it, you get the actual 1 or 0 integer value:
auto sz = stringNumber.size();
for(int i = 0; i < sz; i++) {
result += pow((stringNumber[sz - subtrahend] - '0') * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
Moreover, use the methods provided by std::string like .size() instead of doing strlen() on every iteration. Much faster.
In a production environment, I would highly recommend using std::bitset instead of rolling your own solution:
std::string stringNumber = "1111";
std::bitset<64> bits(stringNumber);
bits.to_ulong();

You're forgetting to convert your digits into integers. Plus you really don't need to use C strings.
Here's a better version of the code
int main() {
std::string stringNumber = "101110111";
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < stringNumber.size(); i++) {
result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Subtracting '0' from the string digits converts the digit into an integer.
Now for extra credit write a version that doesn't use pow (hint: potency *= 2; instead of potency++;)

c++ way
#include <string>
#include <math.h>
#include <iostream>
using namespace std;
int main() {
std::string stringNumber = "101110111";
long long result = 0;
uint string_length = stringNumber.length();
for(int i = 0; i <string_length; i++) {
if(stringNumber[i]=='1')
{
long pose_value = pow(2, string_length-1-i);
result += pose_value;
}
}
std::cout << result << std::endl;
}

Related

Incorrect addition in a Function

I am writing a function in C++ to convert a number from some base to decimal.
It works fine when the number of digits is even, but when it is odd it gives wrong answer.
For example:
Number to convert : 100
Base to convert to: 10
Correct answer : 100
Function's output : 99
Here is the code:
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
for(int i = 0, len = number.size(); i<len; ++i)
{
res += characters.find(number.at(i))*std::pow(base, len-1-i);
}
return res;
}
I'm using g++ C++11.
I can't reproduce your particular issue, but std::pow returns a floating point number and your implementation may have introduced some sort of rounding error which leaded to a wrong result when converted to unsigned long long.
To avoid those errors, when dealing with integer numbers, you should consider to avoid std::pow at all. Your function, for example, could have been written like this:
#include <iostream>
#include <string>
#include <cmath>
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
unsigned long long power = 1;
for(auto i = number.crbegin(); i != number.crend(); ++i)
{
// As in your code, I'm not checking for erroneous input
res += characters.find(*i) * power;
power *= base;
}
return res;
}
int main ()
{
std::cout << convertToDecimal("100", 2) << '\n'; // --> 4
std::cout << convertToDecimal("1234", 8) << '\n'; // --> 668
std::cout << convertToDecimal("99999", 10) << '\n'; // --> 99999
std::cout << convertToDecimal("fedcba", 16) << '\n'; // --> 16702650
}

Store a non numeric string as binary integer [duplicate]

This question already has answers here:
Fastest way to Convert String to Binary?
(3 answers)
Closed 5 years ago.
How do I convert a string like
string a = "hello";
to it's bit representation which is stored in a int
int b = 0110100001100101011011000110110001101111
here a and b being equivalent.
You cannot store a long character sequence (e.g. an std::string) inside an int (or inside a long int) because the size of a character is usually 8-bit and the length of an int is usually 32-bit, therefore a 32-bit long int can store only 4 characters.
If you limit the length of the number of characters, you can store them as the following example shows:
#include <iostream>
#include <string>
#include <climits>
int main() {
std::string foo = "Hello";
unsigned long bar = 0ul;
for(std::size_t i = 0; i < foo.size() && i < sizeof(bar); ++i)
bar |= static_cast<unsigned long>(foo[i]) << (CHAR_BIT * i);
std::cout << "Test: " << std::hex << bar << std::endl;
}
Seems like a daft thing to do, bit I think the following (untested) code should work.
#include <string>
#include <climits>
int foo(std::string const & s) {
int result = 0;
for (int i = 0; i < std::min(sizeof(int), s.size()); ++i) {
result = (result << CHAR_BIT) || s[i];
}
return result;
}
int output[CHAR_BIT];
char c;
int i;
for (i = 0; i < CHAR_BIT; ++i) {
output[i] = (c >> i) & 1;
}
More info in this link: how to convert a char to binary?

C++ Difference between the sum of the squares of the first ten natural numbers and the square of the sum

i wrote a code that calculates and outputs a difference between the sum of the squares of the first ten natural numbers and the square of the sum.
The problem is with function squareOfSum(). The function should return 3025 but it always returns 3024. Even if i try to put 100 into brackets i get 25502499 (25502500 is correct). No matter what number i put into brackets i always get the same problem.
What am I doing wrong?
Here's a screenshot of my output.
#include <iostream>
#include <cmath>
using namespace std;
int sumOfSquares(int limit);
int squareOfSum(int limit);
int main()
{
cout << sumOfSquares(10) << endl;
cout << squareOfSum(10) << endl;
cout << squareOfSum(10) - sumOfSquares(10) << endl;
}
int sumOfSquares(int limit)
{
int sum = 0;
for(int i = 1; i<=limit; i++)
{
sum +=pow(i,2);
}
return sum;
}
int squareOfSum(int limit)
{
int sum = 0, square = 0;
for(int i = 1; i<=limit; i++)
{
sum +=i;
}
square = pow(sum,2);
return square;
}
Note that pow is a function that works with floating point numbers. Optimizations might lead to rounding errors or truncation during implicit coversion to int. Replace pow(i, 2) with i*i and you'll get pure integer arithmetic and thus exact results.
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int higher_limit = 100;
int SquaresOfSum = 0;
int SumOfSquares = 0,count=0;
for(int i=1;i<=higher_limit;i++){
count += i;
SumOfSquares += pow(i,2);
}
SquaresOfSum = pow(count,2);
cout<<SquaresOfSum-SumOfSquares;
}
Using Javascript
const sumSquareDifference = (n) => {
const numbers = [...Array(n + 1).keys()];
const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));

Converting an array of 2 digit numbers into an integer (C++)

Is it possible to take an array filled with 2 digit numbers e.g.
[10,11,12,13,...]
and multiply each element in the list by 100^(position in the array) and sum the result so that:
mysteryFunction[10,11,12] //The function performs 10*100^0 + 11*100^1 + 12*100^3
= 121110
and also
mysteryFunction[10,11,12,13]
= 13121110
when I do not know the number of elements in the array?
(yes, the reverse of order is intended but not 100% necessary, and just in case you missed it the first time the numbers will always be 2 digits)
Just for a bit of background to the problem: this is to try to improve my attempt at an RSA encryption program, at the moment I am multiplying each member of the array by 100^(the position of the number) written out each time which means that each word which I use to encrypt must be a certain length.
For example to encrypt "ab" I have converted it to an array [10,11] but need to convert it to 1110 before I can put it through the RSA algorithm. I would need to adjust my code for if I then wanted to use a three letter word, again for a four letter word etc. which I'm sure you will agree is not ideal. My code is nothing like industry standard but I am happy to upload it should anyone want to see it (I have also already managed this in Haskell if anyone would like to see that). I thought that the background information was necessary just so that I don't get hundreds of downvotes from people thinking that I'm trying to trick them into doing homework for me. Thank you very much for any help, I really do appreciate it!
EDIT: Thank you for all of the answers! They perfectly answer the question that I asked but I am having problems incorporating them into my current program, if I post my code so far would you be able to help? When I tried to include the answer provided I got an error message (I can't vote up because I don't have enough reputation, sorry that I haven't accepted any answers yet).
#include <iostream>
#include <string>
#include <math.h>
int returnVal (char x)
{
return (int) x;
}
unsigned long long modExp(unsigned long long b, unsigned long long e, unsigned long long m)
{
unsigned long long remainder;
int x = 1;
while (e != 0)
{
remainder = e % 2;
e= e/2;
if (remainder == 1)
x = (x * b) % m;
b= (b * b) % m;
}
return x;
}
int main()
{
unsigned long long p = 80001;
unsigned long long q = 70021;
int e = 7;
unsigned long long n = p * q;
std::string foo = "ab";
for (int i = 0; i < foo.length(); i++);
{
std::cout << modExp (returnVal((foo[0]) - 87) + returnVal (foo[1] -87) * 100, e, n);
}
}
If you want to use plain C-style arrays, you will have to separately know the number of entries. With this approach, your mysterious function might be defined like this:
unsigned mysteryFunction(unsigned numbers[], size_t n)
{
unsigned result = 0;
unsigned factor = 1;
for (size_t i = 0; i < n; ++i)
{
result += factor * numbers[i];
factor *= 100;
}
return result;
}
You can test this code with the following:
#include <iostream>
int main()
{
unsigned ar[] = {10, 11, 12, 13};
std::cout << mysteryFunction(ar, 4) << "\n";
return 0;
}
On the other hand, if you want to utilize the STL's vector class, you won't separately need the size. The code itself won't need too many changes.
Also note that the built-in integer types cannot handle very large numbers, so you might want to look into an arbitrary precision number library, like GMP.
EDIT: Here's a version of the function which accepts a std::string and uses the characters' ASCII values minus 87 as the numbers:
unsigned mysteryFunction(const std::string& input)
{
unsigned result = 0;
unsigned factor = 1;
for (size_t i = 0; i < input.size(); ++i)
{
result += factor * (input[i] - 87);
factor *= 100;
}
return result;
}
The test code becomes:
#include <iostream>
#include <string>
int main()
{
std::string myString = "abcde";
std::cout << mysteryFunction(myString) << "\n";
return 0;
}
The program prints: 1413121110
As benedek mentioned, here's an implementation using dynamic arrays via std::vector.
unsigned mystery(std::vector<unsigned> vect)
{
unsigned result = 0;
unsigned factor = 1;
for (auto& item : vect)
{
result += factor * item;
factor *= 100;
}
return result;
}
void main(void)
{
std::vector<unsigned> ar;
ar.push_back(10);
ar.push_back(11);
ar.push_back(12);
ar.push_back(13);
std::cout << mystery(ar);
}
I would like to suggest the following solutions.
You could use standard algorithm std::accumulate declared in header <numeric>
For example
#include <iostream>
#include <numeric>
int main()
{
unsigned int a[] = { 10, 11, 12, 13 };
unsigned long long i = 1;
unsigned long long s =
std::accumulate( std::begin( a ), std::end( a ), 0ull,
[&]( unsigned long long acc, unsigned int x )
{
return ( acc += x * i, i *= 100, acc );
} );
std::cout << "s = " << s << std::endl;
return 0;
}
The output is
s = 13121110
The same can be done with using the range based for statement
#include <iostream>
#include <numeric>
int main()
{
unsigned int a[] = { 10, 11, 12, 13 };
unsigned long long i = 1;
unsigned long long s = 0;
for ( unsigned int x : a )
{
s += x * i; i *= 100;
}
std::cout << "s = " << s << std::endl;
return 0;
}
You could also write a separate function
unsigned long long mysteryFunction( const unsigned int a[], size_t n )
{
unsigned long long s = 0;
unsigned long long i = 1;
for ( size_t k = 0; k < n; k++ )
{
s += a[k] * i; i *= 100;
}
return s;
}
Also think about using std::string instead of integral numbers to keep an encrypted result.

Using pow() for large number

I am trying to solve a problem, a part of which requires me to calculate (2^n)%1000000007 , where n<=10^9. But my following code gives me output "0" even for input like n=99.
Is there anyway other than having a loop which multilplies the output by 2 every time and finding the modulo every time (this is not I am looking for as this will be very slow for large numbers).
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
int main()
{
unsigned long long gaps,total;
while(1)
{
cin>>gaps;
total=(unsigned long long)powf(2,gaps)%1000000007;
cout<<total<<endl;
}
}
You need a "big num" library, it is not clear what platform you are on, but start here:
http://gmplib.org/
this is not I am looking for as this will be very slow for large numbers
Using a bigint library will be considerably slower pretty much any other solution.
Don't take the modulo every pass through the loop: rather, only take it when the output grows bigger than the modulus, as follows:
#include <iostream>
int main() {
int modulus = 1000000007;
int n = 88888888;
long res = 1;
for(long i=0; i < n; ++i) {
res *= 2;
if(res > modulus)
res %= modulus;
}
std::cout << res << std::endl;
}
This is actually pretty quick:
$ time ./t
./t 1.19s user 0.00s system 99% cpu 1.197 total
I should mention that the reason this works is that if a and b are equivalent mod m (that is, a % m = b % m), then this equality holds multiple k of a and b (that is, the foregoing equality implies (a*k)%m = (b*k)%m).
Chris proposed GMP, but if you need just that and want to do things The C++ Way, not The C Way, and without unnecessary complexity, you may just want to check this out - it generates few warnings when compiling, but is quite simple and Just Works™.
You can split your 2^n into chunks of 2^m. You need to find: `
2^m * 2^m * ... 2^(less than m)
Number m should be 31 is for 32-bit CPU. Then your answer is:
chunk1 % k * chunk2 * k ... where k=1000000007
You are still O(N). But then you can utilize the fact that all chunk % k are equal except last one and you can make it O(1)
I wrote this function. It is very inefficient but it works with very large numbers. It uses my self-made algorithm to store big numbers in arrays using a decimal like system.
mpfr2.cpp
#include "mpfr2.h"
void mpfr2::mpfr::setNumber(std::string a) {
for (int i = a.length() - 1, j = 0; i >= 0; ++j, --i) {
_a[j] = a[i] - '0';
}
res_size = a.length();
}
int mpfr2::mpfr::multiply(mpfr& a, mpfr b)
{
mpfr ans = mpfr();
// One by one multiply n with individual digits of res[]
int i = 0;
for (i = 0; i < b.res_size; ++i)
{
for (int j = 0; j < a.res_size; ++j) {
ans._a[i + j] += b._a[i] * a._a[j];
}
}
for (i = 0; i < a.res_size + b.res_size; i++)
{
int tmp = ans._a[i] / 10;
ans._a[i] = ans._a[i] % 10;
ans._a[i + 1] = ans._a[i + 1] + tmp;
}
for (i = a.res_size + b.res_size; i >= 0; i--)
{
if (ans._a[i] > 0) break;
}
ans.res_size = i+1;
a = ans;
return a.res_size;
}
mpfr2::mpfr mpfr2::mpfr::pow(mpfr a, mpfr b) {
mpfr t = a;
std::string bStr = "";
for (int i = b.res_size - 1; i >= 0; --i) {
bStr += std::to_string(b._a[i]);
}
int i = 1;
while (!0) {
if (bStr == std::to_string(i)) break;
a.res_size = multiply(a, t);
// Debugging
std::cout << "\npow() iteration " << i << std::endl;
++i;
}
return a;
}
mpfr2.h
#pragma once
//#infdef MPFR2_H
//#define MPFR2_H
// C standard includes
#include <iostream>
#include <string>
#define MAX 0x7fffffff/32/4 // 2147483647
namespace mpfr2 {
class mpfr
{
public:
int _a[MAX];
int res_size;
void setNumber(std::string);
static int multiply(mpfr&, mpfr);
static mpfr pow(mpfr, mpfr);
};
}
//#endif
main.cpp
#include <iostream>
#include <fstream>
// Local headers
#include "mpfr2.h" // Defines local mpfr algorithm library
// Namespaces
namespace m = mpfr2; // Reduce the typing a bit later...
m::mpfr tetration(m::mpfr, int);
int main() {
// Hardcoded tests
int x = 7;
std::ofstream f("out.txt");
m::mpfr t;
for(int b=1; b<x;b++) {
std::cout << "2^^" << b << std::endl; // Hardcoded message
t.setNumber("2");
m::mpfr res = tetration(t, b);
for (int i = res.res_size - 1; i >= 0; i--) {
std::cout << res._a[i];
f << res._a[i];
}
f << std::endl << std::endl;
std::cout << std::endl << std::endl;
}
char c; std::cin.ignore(); std::cin >> c;
return 0;
}
m::mpfr tetration(m::mpfr a, int b)
{
m::mpfr tmp = a;
if (b <= 0) return m::mpfr();
for (; b > 1; b--) tmp = m::mpfr::pow(a, tmp);
return tmp;
}
I created this for tetration and eventually hyperoperations. When the numbers get really big it can take ages to calculate and a lot of memory. The #define MAX 0x7fffffff/32/4 is the number of decimals one number can have. I might make another algorithm later to combine multiple of these arrays into one number. On my system the max array length is 0x7fffffff aka 2147486347 aka 2^31-1 aka int32_max (which is usually the standard int size) so I had to divide int32_max by 32 to make the creation of this array possible. I also divided it by 4 to reduce memory usage in the multiply() function.
- Jubiman