this code finds the binary of a decimal integer N; it divides the number by 2 and takes the floor of the result and divides it also by 2,
the code gets the remainder of those divisions 0 or 1 and builds up the binary.
The problem with this code is that it won't run until the last division example (take 128 the last division is 1/2 and remainder is 1, the program stops at N/2 > 0 as specified in the while loop and 1/2 = 0 since 1 is of type int).
How do I resolve this issue or how do I modify the condition in the while loop?
#include <iostream>
using namespace std;
void ConvertToBinary(int N);
int main()
{
int N = 1;
while (1)
{
cout << "enter N: ";
cin >> N;
cout << endl;
ConvertToBinary(N);
cout << endl;
}
system("pause");
return 0;
}
void ConvertToBinary(int N)
{
int A[1000];
int i=0;
cout << "The binary of " << N << "= ";
while (N / 2 > 0)
{
if (N % 2 == 0)
{
A[i] = 0;
}
else if (N % 2 != 0)
{
A[i] = 1;
}
N = N / 2;
i++;
}
for (int j= i-1 ; j>=0 ; j--)
{
cout<<A[j];
}
cout << endl;
}
N is not "a decimal integer". It is a number.
If you really want to talk specifics, it's already stored in binary.
What you're talking about is representation. What is the representation of the number when printed to screen? IOStreams by default will show you numbers in decimal.
You can use I/O Manipulators, though, to choose hexadecimal or octal instead. Sadly there isn't a std::bin yet, but we can use std::bitset for the same purpose:
#include <iostream>
#include <iomanip>
#include <bitset>
int main()
{
int x = 42;
std::cout << x << '\n';
std::cout << std::hex << x << '\n';
std::cout << std::oct << x << '\n';
std::cout << std::bitset<sizeof(x)>(x) << '\n';
}
// Output:
// 42
// 2a
// 52
// 1010
(live demo)
And your whole approach (to "fake" a representation shift by changing your number to another number that happens to look like the binary representation of the original number when you print it in decimal representation — phew!) becomes obsolete, solving your problem effortlessly.
Related
#include <iostream>
using namespace std;
int enough(int goal)
{
int C { };
int i { };
if (goal > 1)
{
while (((C += i) <= goal) && ((goal - i) <= (i + 1)))
{
i += 1;
}
}
else
{
i = 1;
}
return i;
}
int main()
{
cout << enough(21);
return 0;
}
So the purpose of this function is for it to return the smallest positive integer that can be summed consecutively from 1 before the cumulative sum becomes greater than the parameter "goal".
So, for example:
cout << enough(9) << endl;
will print 4 because 1+2+3+4 > 9 but 1+2+3<9
cout << enough(21) << endl;
will print 6 'cause 1+2+ . . .+6 > 21 but 1+2+ . . . 5<21
cout << enough(-7) << endl;
will print 1 because 1 > -7 and 1 is the smallest positive integer
cout << enough(1) << endl;
will print 1 because 1 = 1 and 1 is the smallest positive integer
My logic at first was using just while ((C += i) <= goal), but that went wrong, for example, for the parameter 21, where you get C = 20, which passes the test and ends up in i being augmented by 1 (resulting in the return value i = 7, which is clearly wrong).
Therefore I decided to create a test which tested both C and i, but that went wrong because the code isn't considering goal - i and i + 1 as separate tests for the while circuit, but I believe it is actually altering the value of ints goal and i, which screws everything up.
Any ideas where I went wrong?
Your approach is unnecessarily verbose. There is a closed-form (i.e. O(1)) solution for this.
The sum S of the arithmetic progression 1, 2, ..., n is
S = n * (n + 1) / 2
Rearranging this (completing the square), rejecting the spurious root, and rounding appropriately to fit the requirements of the question yields the result
n = std::ceil((-1 + std::sqrt(1 + 8 * S)) / 2)
This will not work for negative n, and possibly 0 too depending on the specific (and unspecified) requirements.
Or if you must use an O(N) approach, then
int enough(int goal){
int i = 0;
for (int total = 0; (total += ++i, total) < goal; );
return i;
}
will do it, which returns 1 for goal <= 1.
You could perhaps try to simplify your original O(N) approach by only having one condition in your while-loop, i.e., no &&:
#include <iostream>
using namespace std;
int enough(int goal)
{
if (goal <= 0)
{
return 1;
}
int total{};
int i{};
while (total < goal)
{
total += ++i;
}
return i;
}
int main()
{
cout << "enough(9): " << enough(9) << endl;
cout << "enough(21): " << enough(21) << endl;
cout << "enough(-7): " << enough(-7) << endl;
cout << "enough(1): " << enough(1) << endl;
cout << "enough(0): " << enough(0) << endl;
return 0;
}
Output:
enough(9): 4
enough(21): 6
enough(-7): 1
enough(1): 1
enough(0): 1
I am kinda a newbie in C++ and I am a having hard time with a situation.
My task is to create a decimal to [2:9] number system conversion. I am dividing the input number to the base and then, taking the quotient as the divident and continuing the same process.
For example if the decimal number is 149 and that number is calculated on base 2, my output is like this:
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 0
Remainder 1
The outputs are the elements of an array named remainder.
And then I have to merge these array elements in reverse order (1001010) to form the new base number as an integer. How can I do this? I am stuck at this point. The above output is just the part of my output. The number will be prompted from user and it is going to be calculated on bases from 2 to 9. So, array lenghts may change (I have the code for the digit calculation, I have no issues with that).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int merge(int a[]);
int main(int argc, char*argv[])
{
int dNumber;
int system[8];
for (int i = 0; i < 8; i++)
{
system[i] = i + 2;
}
cout << "Please enter the decimal base number which you want to use in the conversion: " << endl;
cin >> dNumber;
int permanent = dNumber; //to keep the input number intact as it changes through the loops (used in line 53)
int ndigits[8]={1};
for (int i = 0; i < 8; i++)
{
while(dNumber > pow(system[i], ndigits[i]))
{
ndigits[i] ++;
}
}
int dNumberNew = dNumber;
for (int k = 0; k < 8; k++){
for (int i=0; i>=0; i++)
{
int Remainder[i], quotient[i];
Remainder[i] = dNumberNew % system[k];
quotient[i] = dNumberNew / system[k]; // since the variables are integers, this line does not assign decimals and finds the quotient easily.
cout << dNumberNew << " " << system[k] << "'e bolundu. " << "Sonuc " << quotient[i] << " Kalan " << Remainder[i] << " cikti." << endl;
dNumberNew = quotient[i];
if (quotient[i] == 0)
{
break;
}
}
cout << "(" << dNumber << ")" << "_(" << system[k] << ")" << "=" << endl;
cout << "" << endl;
dNumberNew = permanent;
}
}
Here is a function you can use as DecimalToBinary converter, analyze the code yourself
string toBinary(unsigned long long* arr, unsigned long long size) {
string answer;
for (unsigned long long i = 1; i < size; i++) {
string binaryNum = "";
while (arr[i] >= 1) {
binaryNum = static_cast<char>((arr[i] % 2) + '0') + binaryNum;
arr[i] = arr[i] / 2;
}
answer += binaryNum + " ";
}
return answer;
}
am running these two functions that do the same calculation "summing the first N integers " then compare the run times for each one. The program works fine with small inputs, but the problem is when I input large numbers like 1000000, it calculates the first method "the iterativeSum()" then as soon as it gets to the the recursiveSum() it stops working.
am not sure but do you think that this might be because of the cout?
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void iterativeSum(int);
int RecursiveSum(int);
int main()
{
long long posInt;
std::cout << "Enter a positive integer: ";
std::cin >> posInt;
int start_s=clock();
iterativeSum(posInt);
int stop_s=clock();
int start_s1=clock();
cout << "\nThe recursive algorithm to sum the first N integers of "<< posInt << " is: "<< RecursiveSum(posInt) << endl;
int stop_s1=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)/1000 << endl;
cout << "time: " << (stop_s1-start_s1)/double(CLOCKS_PER_SEC)/1000 << endl;
return 0;
}
void iterativeSum(int posInt)
{
//positive Integer >=0
int sum = 0;
//loop through and get only postive integers and sum them up.
// postcondion met at i = 0
for(int i = 0; i <= posInt;i++)
{
sum +=i;
}
//output the positive integers to the screen
std::cout <<"\nThe iterative algorithm to sum the first N integers of " <<posInt <<" is: " << sum << "\n";
}
int RecursiveSum(int n)
{
if(n == 1) // base case
{
return 1;
}
else
{
return n + RecursiveSum(n - 1); //This is n + (n - 1) + (n - 2) ....
}
}
You may need an arbitrary precision arithmetic library like GMPlib, to avoid arithmetic overflows. And you should be afraid of stack overflow.
The call stack is often limited (to e.g. a megabyte). See this
I have with my code. This is about recursion. I have to create function digitAppear( int findDigit, int value) where value is the user input, and findDigit is single digit number ranging from 0 to 9. The function read user input and return each digit number from the user input and count how many times each digit number occurs in the user input. For example, if I type 1234 then the output say 1 appear 1 time, 2 appear 1 time and so on (I hope my explanation is clear) The problem is the only run once and can only return 1 value.
#include <iostream>
using namespace std;
int countOccurence(int, int);
int main()
{
int findDig;
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 9999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
cin >> value; //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
}
//process the value
for (findDig = 0; findDig < 9; findDig++)
{
cout << endl;
cout << cout << "the " << findDig << "appear in digit " << value << " is " << countOccurence(findDig, value) << " times" << endl;
}
//countOccurance(findDig, value);
//cout
}
int countOccurence(int findDig, int value)
{
int n = value;
while( n > 10 )
{
int a = n / 10; //eliminate the right most integer from the rest
int aa = n % 10; //separate the right most integer from the rest
int b = a / 10; //eliminate the second integer from the rest
int bb = a % 10; //separate the second integer from the rest
int c = b / 10; // eliminate the third integer from the rest
int cc = b % 10; //separate the third integer from the rest
for (findDig = 0; findDig < 9; findDig++)
{
int i = 0;
if (findDig == aa) // see if the findDigit value is equal to single digit of b;
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == bb)
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == cc)
{
i += 1;
} else
{
i += 0;
}
return il;
}
}
}
The problem is my function countOccurence() doesn't seems right. I wonder if there a way to do it. I have been stuck with this for days and I really appreciate your input, thank you.
To use recursion, you must think about the problem in a different way.
The easiest way of thinking about how you could incorporate recursion into the function is the process of 'peeling off' each number.
A very simple way of doing this is by looking at the first/last digit in the number, compute that, then call itself on the remainder of the number.
Hopefully you can figure out the code from there.
If you mean that function digitAppear itself has to be recursive then it can look the following way as it is shown in the demonstrative program below
#include <iostream>
#include <cstdlib>
size_t digitAppear( int findDigit, int value )
{
return ( std::abs( value ) % 10u == std::abs( findDigit ) ) +
( ( value /= 10 ) ? digitAppear( findDigit, value ) : 0 );
}
int main()
{
int i = 0;
for ( int x : { 0, 11111, 1234, 34343 } )
{
std::cout << "There are " << digitAppear( i, x )
<< " digit " << i
<< " in number " << x
<< std::endl;
++i;
}
return 0;
}
The program output is
There are 1 digit 0 in number 0
There are 5 digit 1 in number 11111
There are 1 digit 2 in number 1234
There are 3 digit 3 in number 34343
Of course you may rewrite function main as you like for example that it would count each digit in a number.
Hi can anyone help me in creating a code for the sum of input number in C++.
e.g.
Input: 535
Output: 13
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int i = 0,sum = 0;
int numarray[50];
void calc(int c,string num) {
do {
numarray[i] = num.at(i);
/*sum = sum + numarray[i];*/
sum = sum + num.at(i);
cout << numarray[i] << endl;
i++;
} while(i != c);
cout << sum << endl;
}
int main() {
string num;
int i,charlen;
int numar[50];
int sum=0;
cout << "Input numbers: ";
cin >> num;
charlen = num.length();
calc(charlen,num);
}
While characters are numbers, their values are often not the same as the character they represent. The most common encoding scheme is ASCII encoding.
As you can see in the linked table, the digits don't have the value 1 or 2 etc. Instead they have values like 49 and 50 etc. The characters '5' and '3' have the ASCII values 53 and 51 respectively, adding e.g. "535" will give you the result 157.
But as you can see in the ASCII table, all numbers are consecutive, that means we can use a very simple trick to get the digits value from its ASCII value, simply subtract the ASCII value of '0'. For example '5' - '0' will give you the value 5.
Without testing:
#include <iostream>
int main()
{
unsigned long long x;
std::cout << "Enter a non-negative number: ";
std::cin >> x;
unsigned long long sum = 0;
do { sum += x % 10; } while ( x /= 10 );
std::cout << "\nThe sum of digits of the number is " << sum << std::endl;
}
For the sake of readability, it might help to not pass in the charlength into the function, and just do that inside the method. Besides that, a for loop seems like a better option in this case as well.
void calc(string num) {
int sum = 0, int i = 0;
//for loop run from num.length - 1 to 0 {
/*numarray[i] = stoi(num.at(i));*/
/*sum = sum + numarray[i];*/
sum = sum + stoi(num.at(i));
cout << numarray[i] << endl;
i++;
}
cout << sum << endl;
}