Optimizing conversion algorithm - c++

I have recently been working on a exercise in a book I have been reading. The task was to create a program that prints all the numbers between 1-256 in their binary, octal and hexadecimal equivalents. We were only supposed to use methods we had learned so far in the book, which meant only using for, while and do..while loops, if and else if statements, converting integers to ASCII equivalents and some more basic stuff (e.g. cmath and iomanip).
So after some work, here is my result. However, it is messy and un-elegant and obfuscated. Does anyone have any suggestions to increase code efficiency (or elegance... :P) and performance?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int decimalValue, binaryValue, octalValue, hexadecimalValue, numberOfDigits;
cout << "Decimal\t\tBinary\t\tOctal\t\tHexadecimal\n\n";
for (int i = 1; i <= 256; i++)
{
binaryValue = 0;
octalValue = 0;
hexadecimalValue = 0;
if (i != 0)
{
int x, j, e, c, r = i, tempBinary, powOfTwo, tempOctal, tempDecimal;
for (j = 0; j <=8; j++) //Starts to convert to binary equivalent
{
x = pow(2.0, j);
if (x == i)
{
powOfTwo = 1;
binaryValue = pow(10.0, j);
break;
}
else if (x > i)
{
powOfTwo = 0;
x /= 2;
break;
}
}
if (powOfTwo == 0)
{
for (int k = j-1; k >= 0; k--)
{
if ((r-x)>=0)
{
r -= x;
tempBinary = pow(10.0, k);
x /= 2;
}
else if ((r-x)<0)
{
tempBinary = 0;
x /= 2;
}
binaryValue += tempBinary;
}
} //Finished converting
int counter = ceil(log10(binaryValue+1)); //Starts on octal equivalent
int iter;
if (counter%3 == 0)
{
iter = counter/3;
}
else if (counter%3 != 0)
{
iter = (counter/3)+1;
}
c = binaryValue;
for (int h = 0; h < iter; h++)
{
tempOctal = c%1000;
int count = ceil(log10(tempOctal+1));
tempDecimal = 0;
for (int counterr = 0; counterr < count; counterr++)
{
if (tempOctal%10 != 0)
{
e = pow(2.0, counterr);
tempDecimal += e;
}
tempOctal /= 10;
}
octalValue += (tempDecimal * pow(10.0, h));
c /= 1000;
}//Finished Octal conversion
cout << i << "\t\t" << binaryValue << setw(21-counter) << octalValue << "\t\t";
int c1, tempHex, tempDecimal1, e1, powOf;
char letter;
if (counter%4 == 0)//Hexadecimal equivalent
{
iter = counter/4;
}
else if (counter%4 != 0)
{
iter = (counter/4)+1;
}
c1 = binaryValue;
for (int h = 0, g = iter-1; h < iter; h++, g--)
{
powOf = g*4;
if (h == 0)
{
tempHex = c1 / pow(10.0, powOf);
}
else if (h > 0)
{
tempHex = c1 / pow(10.0, powOf);
tempHex %= 10000;
}
int count = ceil(log10(tempHex+1));
tempDecimal1 = 0;
for (int counterr = 0; counterr < count; counterr++)
{
if (tempHex%10 != 0)
{
e1 = pow(2.0, counterr);
tempDecimal1 += e1;
}
tempHex /= 10;
}
if (tempDecimal1 <= 9)
{
cout << tempDecimal1;
}
else if (tempDecimal1 > 9)
{
cout << char(tempDecimal1+55); //ASCII's numerical value for A is 65. Since 10-15 are supposed to be letters you just add 55
}
}
cout << endl;
}
}
system("pause");
return 0;
}
Any recommendations for improvement will be appreciated.

You have already covered 'iomanip', which infers you've already covered 'iostream'.
If that's the case, have a look at the following:
#include <iostream>
#include <iomanip>
using namespace std;
int x = 250;
cout << dec << x << " "
<< oct << x << " "
<< hex << x << "\n"
<< x << "\n"; // This will still be in HEX

Break out the functions for each output type, then loop through the integer list and output each in turn by calling the function for each different format.
for (int i = 1; i <= 256; ++i)
{
printBin(i);
printHex(i);
printOct(i);
}
Fundamental problem is that a function this long needs refactoring to be more modular. Imagine you are writing the code for someone else to use. How can they call your main? How do they understand what each section of code is doing? They can't. If you make each section of code that has a particular job to do callable as a function then it's easier to understand its intent, and to reuse later.

Have you considered writing a general function that works with any base?
Converting a non-negative number to a generic base is simple... you just need to compute number % base and you get the least significant digit, then divide number by base and repeat to get other digits...
std::string converted_number;
do {
int digit = number % base;
converted_number = digits[digit] + converted_number;
number = number / base;
} while (number != 0);
Once you have a generic conversion function then solving your problem is easy... just call it with base=2, 8 and 16 to get the results you need as strings.

My answer may be a bit tongue in cheek, but
printf ("%u %o %x \n", value, value, value);
will do the trick for the octal and hexadecimal versions ;)
For the binary version, i'd use a flag initialized to 256, and compare it to your number with the AND operator. If true, print a 1, if not, print a 0. Then divide the flag by two. Repeat until the flag is 1.
Pseudocode for the conversion from integer to binary
int flag = 256
do
{
if (flag && value)
print "1"
else
print "0"
flag = flag >> 1 // aka divide by two, if my memory serves well
} while flag > 1
For the octal and hex values, i'm a bit rusty but looking around should guide you to samples you may adapt

Why make it any harder than it really is.
for (int i = 1; i <= 256; ++i)
{
std::cout << std::dec << i << "\t" << std::oct << i << "\t" << std::hex << i << std::endl;
}

Try this
using namespace std;
template <typename T>
inline void ShiftMask(T& mask) {
mask = (mask >> 1) & ~mask;
}
template < typename T >
std::ostream& bin(T& value, std::ostream &o)
{
T mask = 1 << (sizeof(T) * 8 - 1);
while (!(value & mask) && (mask != 0)) ShiftMask(mask);
while (mask) {
o << (value & mask ? '1' : '0');
ShiftMask(mask);
}
return o;
}
int main(void) {
for (int i=0; i<256;i++) {
bin(a, std::cout);
cout << " " << oct << i;
cout << " " << dec << i;
cout << " " << hex << i;
cout << ""
}
}

Maybe something like this?
#include "stdio.h"
int main(){
char Chars[16]= {48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70};
for(int n = 1;n != 256; n++)
{
{//decimal
printf("%i\t", n);
}
{//Hexadecimal
char L, R;
R = (n & 0x0F) >> 0;
L = (n & 0xF0) >> 4;
printf("%c%c\t", Chars[L], Chars[R]);
}
{//Octal
char L, M, R;
R = (n & 0x07) >> 0;
M = (n & 0x38) >> 3;
L = (n & 0xC0) >> 6;
printf("%c%c%c\t", Chars[L], Chars[M], Chars[R]);
}
{//Binary
char B0, B1, B2, B3, B4, B5, B6, B7;
B0 = (n & 0x01) >> 0;
B1 = (n & 0x02) >> 1;
B2 = (n & 0x04) >> 2;
B3 = (n & 0x08) >> 3;
B4 = (n & 0x10) >> 4;
B5 = (n & 0x20) >> 5;
B6 = (n & 0x40) >> 6;
B7 = (n & 0x80) >> 7;
printf("%c%c%c%c%c%c%c%c\n", Chars[B0], Chars[B1], Chars[B2], Chars[B3], Chars[B4], Chars[B5], Chars[B6], Chars[B7]);
}
printf("256\t100\t400\t100000000\n");
}
}

Related

Write a C++ program to find kernel in boolean expression

I am a college student, and I have a programming assignment asked us to find kernels in boolean expression. The document teacher provide has a sample pseudo code to guide us how to write a program. The pseudo code is as below.
// Kernel Algorithm
FindKernels(cube-free SOP expression F) // F: input Boolean function
{
K = empty; // K: list of kernel(s)
for(each variable x in F)
{
if(there are at least 2 cubes in F that have variable x)
{
let S = {cubes in F that have variable x in them};
let co = cube that results from intersection of all cubes
in S, this will be the product of just those literals that appear in
each of these cubes in S;
K = K ∪ FindKernels(F / co);
}
}
K = K ∪ F ;
return( K )
}
But I don.t know what is the meaning of the definition of "co". As what I understand S is those terms that have the variable X. Take "abc + abd + bcd = b(ac + ad + cd)" for example, S = {abc, abd, bcd}. But what is co??
I also write another program
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void find_kernels(vector<string> &terms);
bool eliminate_char(string &doing, char eliminate);
void eliminate_char_complete(vector<string> &terms, char eliminate);
int main()
{
string file_name;
vector<string> expression;
vector<string> expression_name;
string expression_temp, expression_name_temp, input_untruncated;
vector<vector<string>> terms;//break each expression into each term
here:
cout << "Please enter the file name that you want to load: ";
cin >> file_name;
ifstream load_file(file_name, ios::in);
if(!load_file)
{
cout << "The file you choose cannot be opened!\n";
goto here;
}
there:
cout << "Please enter the name of the output file: ";
cin >> file_name;
ofstream output_file(file_name, ios::out);
if(!output_file)
{
cout << "The file cannot be created!\n";
goto there;
}
while(load_file >> input_untruncated)
{
expression_name_temp = input_untruncated.substr(0, input_untruncated.find("="));
expression_temp = input_untruncated.substr(input_untruncated.find("=") + 1);
expression_name.push_back(expression_name_temp);
expression.push_back(expression_temp);
}
//start to truncate every terms
for(int i = 0 ; i < (int)expression.size() ; i++)
{
int j = 0;
int k = 0;//k >> last time location
vector<string> terms_temp_vector;
string terms_temp;
string expression_trans = expression[i];
while(j < (int)expression[i].size())
{
if(expression_trans[j] == '+' || expression_trans[j] == '-')
{
terms_temp = expression_trans.substr(k, j - k);
terms_temp_vector.push_back(terms_temp);
k = j + 1;
}
j++;
}
terms_temp = expression_trans.substr(k);
terms_temp_vector.push_back(terms_temp);
terms.push_back(terms_temp_vector);
}
/*for(int i = 0 ; i < (int)expression.size() ; i++)
{
cout << "expression_name: " << expression_name[i] << endl;
cout << expression[i] << endl;
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}*/
cout << endl;
for(int i = 0 ; i < (int)expression.size() ; i++)
{
//output_file << expression_name[i] << endl;
//output_file << expression[i] << endl;
cout << "*";
while(terms[i].size() != 0)
{
find_kernels(terms[i]);
if(terms[i].size() != 0)
{
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}
}
cout << endl;
}
/*for(int i = 0 ; i < (int)expression.size() ; i++)
{
cout << "expression_name: " << expression_name[i] << endl;
cout << expression[i] << endl;
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}*/
return 0;
}
void find_kernels(vector<string> &terms)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, g = 0;
for(int i = 0 ; i < (int)terms.size() ; i++)
{
string terms_temp = terms[i];
for(int j = 0 ; j < (int)terms_temp.size() ; j++)
{
switch(terms_temp[j])
{
case 'a':
a++;
break;
case 'b':
b++;
break;
case 'c':
c++;
break;
case 'd':
d++;
break;
case 'e':
e++;
break;
case 'g':
g++;
break;
}
}
}
int compare[] = {a, b, c, d, e, g};
int biggest = 0;
char eliminate;
for(int i = 0 ; i < 6 ; i++)
{
if(compare[i] > biggest)
{
biggest = compare[i];
}
}
if(biggest == 1)
{
terms.erase(terms.begin(), terms.end());
return;
}
if(biggest == a)
{
eliminate = 'a';
eliminate_char_complete(terms, eliminate);
}
if(biggest == b)
{
eliminate = 'b';
eliminate_char_complete(terms, eliminate);
}
if(biggest == c)
{
eliminate = 'c';
eliminate_char_complete(terms, eliminate);
}
if(biggest == d)
{
eliminate = 'd';
eliminate_char_complete(terms, eliminate);
}
if(biggest == e)
{
eliminate = 'e';
eliminate_char_complete(terms, eliminate);
}
if(biggest == g)
{
eliminate = 'g';
eliminate_char_complete(terms, eliminate);
}
}
bool eliminate_char(string &doing, char eliminate)
{
for(int i = 0 ; i < (int)doing.size() ; i++)
{
if(doing[i] == eliminate)
{
doing.erase (i, 1);
return 1;
}
}
return 0;
}
void eliminate_char_complete(vector<string> &terms, char eliminate)//delete unrelated terms
{
for(int i = 0 ; i < (int)terms.size() ; i++)
{
if(!eliminate_char(terms[i], eliminate))
{
terms.erase(terms.begin() + i);
}
}
}
input file be like
F1=ace+bce+de+g
F2=abc+abd+bcd
I don't obey the pseudo code above.
First, I break them into single terms and push them into a two dimention vector called terms.
terms[expression number][how many terms in one expression]
Second, I call find_kernels. The founction calculate every letters appear how many times in one expression. ps: only a, b, c, d, e, g will appear.
Third, take out the letter that appear the most time. ex: a, ab, abc...
Then, eliminate them in every terms of the same expression. If a terms do not have those letters, then delete the term directly.
Continue doing the same thing....
However, the question is that if F1 is abc+abd+bcd, I should output ac+ad+cd c+d a+c a+d, but my program will output ac+ad+cd only, cause abc+abd+bcd = b(ac+ad+cd) >> next round ac+ad+cd. a, c, d all apear twice, so there are deleted together. Nothing left.
Any suggestion to my code or further explination of the pseudo code will be appreciate. Thank you.
In general you should be clear about the problem you want to solve and the applied definitions. Otherwise you will always run into severe troubles.
Here you want to calculate the kernels of a boolean expression given in SOP (sum over products form, e.g., abc+cde).
A kernel of a boolean expression F is a cube-free expression that results when you divide F by a single cube.
That single cube is called a co-kernel. (This is the co in the pseudo code)
From a cube-free expression you cannot factor out a single cube that leaves behind no remainder.
Examples
F=ae+be+cde+ab
Kernel Co-Kernel
{a,b,cd} e
{e,b} a
{e,cd} b
{ae,be, cde, ab} 1
F=ace+bce+de+g
Kernel Co-Kernel
{a,b} c
{ac, bc, d} e
As you can see the co-kernel is the variable that you eliminate plus all other common variables that occur in the cubes containing the variable.
To implement that you apply this procedure now recursicely for each variable and store all kernel you create. Essentially thats all!
Practically, for an implementation I would propose to use some more handy encoding of the terms and not strings. As your input seems to only single letter variables you can map it to single bits in uint64 (or even uint32 when only lower case is considered). This will give an straight forward implementation like that (thought, it is optimzed for simplicity not performance):
#include <iostream>
#include <vector>
#include <string>
#inlcude <set>
void read_terms();
uint64_t parse_term(string sterm);
void get_kernels(vector<uint64_t>& terms, vector<pair<vector<uint64_t>, uint64_t> >& kernels);
string format_kernel(vector<uint64_t>& kernel);
int main()
{
read_terms();
return 0;
}
/*
Convert a cube into a string
*/
string cube_to_string(uint64_t cube) {
string res;
char ch = 'a';
for (uint64_t curr = 1; curr <= cube && ch <= 'z'; curr <<= 1, ch++) {
if ((curr & cube) == 0) {
continue;
}
res += ch;
}
ch = 'A';
for (uint64_t curr = (1<<26); curr <= cube && ch <= 'Z'; curr <<= 1, ch++) {
if ((curr & cube) == 0) {
continue;
}
res += ch;
}
return res;
}
/*
Convert a kernel or some other SOP expression into into a string
*/
string format_kernel(vector<uint64_t>& kernel) {
string res = "";
for (uint64_t k : kernel) {
string t = cube_to_string(k) + "+";
if (t.size() > 1) {
res += t;
}
}
if (res.size() > 0) {
res.resize(res.size() - 1);
}
return res;
}
/*
Queries the expression from the stdin and triggers the kernel calculcation.
*/
void read_terms() {
cout << "Please enter the terms in SOP form (0 to end input):" << endl;
vector<uint64_t> terms;
vector<pair<vector<uint64_t>, uint64_t> > kernels;
string sterm;
cout << "Term: ";
while (cin >> sterm) {
if (sterm == "0") {
break;
}
cout << "Term: ";
terms.push_back(parse_term(sterm));
}
get_kernels(terms, kernels);
set<string> set_kernels;
for (pair<vector<uint64_t>, uint64_t>k : kernels) {
set_kernels.insert(format_kernel(k.first));
}
for (string k : set_kernels) {
cout << k << endl;
}
return;
}
/*
Convert a term given as string into a bit vector.
*/
uint64_t parse_term(string sterm) {
uint64_t res = 0;
for (char c : sterm) {
if (c >= 'a' && c <= 'z') {
res |= 1ull << uint64_t(c - 'a');
}
else if (c >= 'A' && c <= 'Z') {
res |= 1ull << uint64_t(c - 'A' + 26);
}
}
return res;
}
/*
Returns a bitvector having a for a each variable occuring in one or more of the cubes.
*/
uint64_t get_all_vars(vector<uint64_t>& terms) {
uint64_t res = 0;
for (uint64_t t : terms) {
res |= t;
}
return res;
}
/*
Returns a bitvector having a one for each variable that is shared between all cubes.
*/
uint64_t get_common_vars(vector<uint64_t>& terms) {
if( terms.size() == 0 ) {
return 0ull;
}
uint64_t res = terms[0];
for (uint64_t t : terms) {
res &= t;
}
return res;
}
/*
Divides all set variables from the cubes and returns then in a new vector.
*/
void div_terms(vector<uint64_t>& terms, uint64_t vars, vector<uint64_t>& result) {
result.resize(terms.size());
uint64_t rvars = vars ^ ~0ull; //flip all vars
for (size_t i = 0; i < terms.size(); i++) {
result[i] = terms[i] & rvars;
}
}
/*
Core calculation to get the kernels out of an expression.
*/
void get_kernels(vector<uint64_t>& terms, vector<pair<vector<uint64_t>, uint64_t> >& kernels ) {
uint64_t vars = get_all_vars(terms);
for (uint64_t curr = 1; curr <= vars; curr <<= 1) {
if ((curr & vars) == 0) {
continue;
}
vector<uint64_t> curr_terms, curr_div_terms;
for (uint64_t uterm : terms) {
if ((uterm & curr) != 0ull) {
curr_terms.push_back(uterm);
}
}
if (curr_terms.size() > 1) {
uint64_t new_kernel = 0ull;
uint64_t new_co = get_common_vars(curr_terms); // calculate the new co-kernel
div_terms(curr_terms, new_co, curr_div_terms);//divide cubes with new co-kernel
kernels.push_back(pair<vector<uint64_t>, uint64_t>(curr_div_terms, new_co));
get_kernels(curr_div_terms, kernels);
}
}
}
Especially the elimination of kernels that occur several times is not very efficient, as it just happens at the end. Usually you would do this earlier and prevent multiple calculation.
This implementation takes the inputs from the stdin and writes the results to the stdout. So you might change it for using files when using it as your homework.
Thought other implementations like counting the number of occurences and making use out of that is also possible.

Print prime factorization in exponential form in C++

So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.

Change 'parameter' string inside method C++

it is my first question in SO, but I cannot find a good solution for this, not online nor from my brain.
I have a big string of number (over 100 digits) and I need to remove some of its digits to create a number divisible by 8. It is really simple...
However, lets say the only way to create this number is with a number that ends with '2'. In this case I would need to look for proper 10's and 100's digits and it is at this point I cannot find an elegant solution.
I have this:
bool ExistDigit(string & currentNumber, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1; i >= 0; i--) {
currentDigit = -48;//0 in ASC II
currentDigit += currentNumber.back();//sum ASCII's value of char to current Digit
if (currentDigit == look1) {
return true;
}
else
currentNumber.pop_back;
}
return false;
}
It modify the string but since I check for 8's and 0's first, by the time I get to check 2's, the string is empty already. I solved this by creating several copies of the string, but I would like to know if there is a better way and what is it.
I know that if I use ExistDigit(string CurrentNumber, int look1), the string does not get modified, but in this case, it would not help with the 2, because after finding the two I need to look for 1's, 5's and 9's after the 2 in the original string.
What is the correct approach to these kind of problems? I mean, should I stick with changing the string or should I return a value for the position of the 2 (for example) and work from there? If it is good to change the string, how should I do it in order to be able to reuse the original string?
I am new to C++, and coding in general (just started actually) so, sorry if it is a really silly question. Thanks in advance.
EDIT: My call look like this:
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
string answer = "YES";
string strNumber;
//look for 0's and 8's. they are solutions by their own
strNumber = originalNumber;
if (ExistDigit(strNumber, 0)) {
answer += "\n0";
}
else {
strNumber = originalNumber;
if (ExistDigit(strNumber, 8)) {
answer += "\n8";
}
else {
strNumber = originalNumber;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(strNumber, 2)) {
if (ExistDigit(strNumber, 1)) {
}
}
else {
EDIT 2: In case you have the same problem, check the function find_last_of, it is really convenient and solves the problem.
The following code retains your design and should give at least a solution if one exists. The nested if and for can be simplified within a more elegant solution by using a recursive function. With such a recursive function, you could also enumerate all the solutions.
Instead of having multiple copies of the string, you could use an iterator that defines the start of the search. In the code the start variable is this iterator.
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
bool ExistDigit(const string & currentNumber, int& start, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1 - start; i >= 0; i--) {
currentDigit = currentNumber[i] - '0';
if (currentDigit == look1) {
start = length - i;
return true;
}
}
return false;
}
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
stringstream answer;
answer << "YES";
//look for 0's and 8's. they are solutions by their own
int start = 0;
if (ExistDigit(originalNumber, start, 0)) {
answer << "\n0";
}
else {
start = 0;
if (ExistDigit(originalNumber, start, 8)) {
answer << "\n8";
}
else {
start = 0;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(originalNumber, start, 2)) {
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "2";
};
}
};
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "2";
};
}
//look for 'odd'36, 'odd'76, 'even'12, 'even'52, 'even'92
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "6";
};
}
};
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "6";
};
}
//look for 'even'24, 'even'64, 'odd'44, 'odd'84, 'odd'04
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 0; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "4";
};
}
};
for (int look2 = 2; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "4";
};
}
}
}
cout << answer.str() << std::endl;
return 0;
}
Here is a solution when you are looking for a subword composed of successive characters in the decimal textual form.
#include <string>
#include <iostream>
bool ExistDigit(const std::string& number, int look) { // look1 = 2**look
// look for a subword of size look that is divisible by 2**look = 1UL << look
for (int i = (int) number.size()-1; i >= 0; --i) {
bool hasFound = false;
unsigned long val = 0;
int shift = look-1;
if (i-shift <= 0)
shift = i;
for (; shift >= 0; --shift) {
val *= 10;
val += (number[i-shift] - '0');
};
if (val % (1UL << look) == 0)
return true;
};
return false;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
if (ExistsDigit(val, 3) /* since 8 = 2**3 = (1 << 3) */)
std::cout << "have found a decimal subword divisible by 8" << std::endl;
else
std::cout << "have not found any decimal subword divisible by 8" << std::endl;
return 0;
}
If you are likely to find a subword of consecutive bits in the binary form of the number, you need to convert your number in a big integer and then to do similar search.
Here is a (minimal-tested) solution without any call to an external library like gmp to convert the text in a big integer. This solution makes use of bitwise operations (<<, &).
#include <iostream>
#include <string>
#include <vector>
int
ExistDigit(const std::string & currentNumber, int look) { // look1 = 2^look
std::vector<unsigned> bigNumber;
int length = currentNumber.size();
for (int i = 0; i < length; ++i) {
unsigned carry = currentNumber[i] - '0';
// bigNumber = bigNumber * 10 + carry;
for (int index = 0; index < bigNumber.size(); ++index) {
unsigned lowPart = bigNumber[index] & ~(~0U << (sizeof(unsigned)*4));
unsigned highPart = bigNumber[index] >> (sizeof(unsigned)*4);
lowPart *= 10;
lowPart += carry;
carry = lowPart >> (sizeof(unsigned)*4);
lowPart &= ~(~0U << (sizeof(unsigned)*4));
highPart *= 10;
highPart += carry;
carry = highPart >> (sizeof(unsigned)*4);
highPart &= ~(~0U << (sizeof(unsigned)*4));
bigNumber[index] = lowPart | (highPart << (sizeof(unsigned)*4));
}
if (carry)
bigNumber.push_back(carry);
};
// here bigNumber should be a biginteger = currentNumber
for (int i = 0; i < bigNumber.size()*8*sizeof(unsigned); ++i) {
// looks for look consective bits set to '0'
bool hasFound = true;
for (int shift = 0; hasFound && shift < look; ++shift)
if (bigNumber[(i+shift) / (8*sizeof(unsigned))]
& (1U << ((i+shift) % (8*sizeof(unsigned)))) != 0)
hasFound = false;
if (hasFound) { // ok, bigNumber has look consecutive bits set to 0
// test if we are at the end of the bigNumber
int index = (i+look) / (8*sizeof(unsigned));
for (int j = ((i+look+8*sizeof(unsigned)-1) % (8*sizeof(unsigned)))+1;
j < (8*sizeof(unsigned)); j++)
if ((bigNumber[index] & (1U << j)) != 0)
return i; // the result is (currentNumber / (2^i));
while (++index < bigNumber.size())
if (bigNumber[index] != 0)
return i; // the result is (currentNumber / (2^i));
return -1;
};
};
return -1;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
std::cout << val << " is divided by 8 after " << ExistDigit(val, 3) << " bits." << std::endl;
return 0;
}

Recurrence in Math

Sorry this is my first time use stackoverflow.
I dont kow where is the mistake in my code.
Output that i want:
-1+3-5+7-9+11-13+15
RESULT : 8
But Output that is shown
-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
cout << "+";
}
if (i == 1) {
sign = 1;
cout << "-";
}
x = sign * (2 * i - 1);
cout << x;
S = S + x;
}
cout << "\n Result:" << S;
}
problem is in the if condition block where you check i==1
in that loop you are making sign=1 that should be sign=-1
How about improving the logic like following?
#include <iostream>
using namespace std;
int main()
{
int i;
bool sign = true; // signed/minus = true, non-signed/plus = false
int ans = 0;
for( i=1; i<=15; i=i+2){
if( sign == true){
cout << "-" << i;
ans = ans - i;
}
else {
cout << "+" << i;
ans = ans + i;
}
sign = !sign;
}
cout << endl << "RESULT : " << ans << endl;
return 0;
}
Try this code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
else
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
// cout << "+";
}
//else
if (i == 1) {
sign = -1;
//cout << "-";
}
x = sign * (2 * i - 1);
cout <<"\n"<<x;
S = S + x;
//cout<<"S is \n"<<S;
}
cout << "\n Result:" << S;
}
You have put wrong sign when i==1
The problem is that you're starting the calculation with a positive sign (but you're lying to yourself by printing "-").
You can simplify the code and don't need to mess around with pow if you make the obervation that
pow(-1, k) == -1 * pow(-1, k-1)
Starting at pow(-1,0) (that is, 1), you can write:
int main(int argc, char* argv[])
{
int sign = 1; // sign will always hold pow(-1, i).
int sum = 0;
for (int i = 1; i <= 8; i++)
{
sign *= -1;
if (sign > 0) // Since sign starts at -1, we know that i > 1 here
{
std::cout << "+";
}
int term = sign * (2 * i - 1);
std::cout << term;
sum += term;
}
std::cout << " = " << sum << std::endl;
}

C++ binary input as a string to a decimal

I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}