C++ Binary to decimal? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I made a function that converts binary numbers to decimals, but if i go to high on the binary numbers, it just returns 256??? What could cause this? I'm using int variables. Any help would be really appreciated
#include <iostream>
using namespace std;
int FromBin (int n)
{
int increment;
int Result;
increment = 1;
Result = 0;
while(n != 0)
{
if (n % 10 == 1){
Result = Result+increment;
n = n-1;
}
n = n/10;
increment = increment*2;
}
cout<<Result;
}
void ToBin(int n)
{
if (n / 2 != 0) {
ToBin(n / 2);
}
cout<<n % 2;
}
int main()
{
int choice;
int n;
cout<<"Choose a function: press 0 for decimals to binary, press 1 for binary to decimal\n";
cin>>choice;
if (choice == 0){
cout<<"Enter a number: \n";
cin>>n;
ToBin(n);
}
else if (choice == 1){
cout<<"Enter a number: \n";
cin>>n;
FromBin(n);
}
else{
cout<<"Invalid input";
}
}
I'm new to C++ so I don't understand this... :/

This is a cool program you got going on here...
This is what I found for a possible solution to your problem...
/* C++ program to convert binary number into decimal */
#include <iostream>
using namespace std;
int main()
{
long bin, dec = 0, rem, num, base = 1;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout << "The decimal equivalent of " << bin << " : " << dec << endl;
return 0;
}

This is what I think you were shooting for. You can handle larger numbers by switching from int to long.
long fromBin(long n)
{
long factor = 1;
long total = 0;
while (n != 0)
{
total += (n%10) * factor;
n /= 10;
factor *= 2;
}
return total;
}
Live demo

From your comment I can see that you are trying to use it on a number that is just too large for an int variable. Look for limits, as for int I found that maximal value is 2147483647.

Related

How do I prime factorize large numbers?

I'm trying to solve Project Euler third question but while my code works perfectly with small numbers when I try to use big number it doesn't give me any answer.
#include<iostream>
using std :: cout;
using std :: cin;
using std :: endl;
int main()
{
long long int a = 0, bigPrime = 0, smallPrime = 2, prime = 0;
cout << "Please enter a number...!" << endl;
cin >> a;
for(long long int i = 2 ; i < a ; i++)
{
for(long long int c = 2 ; c < i ; c++)
{
if(i % c != 0)
{
prime = i;
}
else
{
prime = 0;
break;
}
}
if(prime > 0 )
{
if(a % prime == 0)
{
bigPrime = prime;
}
}
}
cout << "The biggest prime is = " << bigPrime << endl;
return 0;
}
That's my bad code :)
i am using ubuntu linux and g++
what is wrong with my code and how can i improve it?
You can improve your program using one simple trick:
Every time you find a divisor d, divide your number by d.
That means that for every divisor found, your number gets smaller, making the remaining part easier to factor.
As a bonus, that means you don't need to be so careful about only using primes as divisors. Every time a divisor is found, it's the smallest divisor of the current number, and since it's the smallest divisor, it must be a prime. That saves a whole level of looping.
The factors are extracted in order from smallest to highest, so in the end what you have is the highest prime factor - the answer to this challenge.
This is not a fast algorithm, but 600851475143 is not a large number and this algorithm will factor it no problem.
For examle (on ideone):
for (long long int d = 2; d * d <= a; d++) {
if (a % d == 0) {
a /= d;
d--; // this is to handle repeated factors
}
}
I also used the old d * d <= a trick but you don't even need it here. It helps if the highest factor is high, and in this example it is not.
But the problem states that you just need to find the biggest prime of 600851475143, right? Why don't you just iterate from sqrt(600851475143) to 2 and return the first number that is a prime?
bool isPrime(uint64_t num)
{
bool result = true;
for(uint64_t i = 2; i < std::sqrt(num); ++i)
{
if(num % i == 0)
{
result = false;
break;
}
}
return result;
}
int main()
{
uint64_t num = 600851475143;
uint64_t i = std::sqrt(num);
while (i > 1)
{
i--;
if (num%i != 0) continue;
if (isPrime(i))
{
break;
}
}
std::cout << i << std::endl;
return 0;
}
For sure it can be done faster, but it takes 10ms on my machine, so I guess it's not terrible.
#include <iostream>
using namespace std;
typedef long long ulong;
int main()
{
ulong num = 600851475143;
ulong div = num;
ulong p = 0;
ulong i = 2;
while (i * i <= div)
{
if (div % i == 0)
{
div /= i;
p = i;
}
else {
i++;
}
}
if (div > p)
{
p = div;
}
cout << p << endl;
return 0;
}

Find digital roots of a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is an ACM problem in order to finding the roots of an integer number.
Here is the problem text: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=115
This is my code, but when I submit the code, I get wrong answer. In other side, I've check this code with numbers of integers and I've get the correct answer.
#include <iostream>
using namespace std;
int main() {
unsigned long long cc = 0;
cin >> cc;
while (cc != 0) {
unsigned long long sum = 0;
while (cc > 0) {
sum += cc % 10;
cc = cc / 10;
if (cc == 0 && sum > 9) { cc = sum; sum = 0; }
}
cout << sum;
cin >> cc;
cout << endl;
}
}
Can you please help me?!
Thank you.
The problem is that the input integer is larger than what would fit in an unsigned long long.
Therefore, you need to read the number as a string, and then calculate the digit sum from the string.
The following code will work:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string inStr;
while(cin >> inStr && inStr != "0")
{
unsigned long long cc = 0;
for(string::const_iterator it = inStr.begin(); it!=inStr.end(); ++it)
{
cc += *it - '0';
}
unsigned long long sum = 0;
do
{
while (cc)
{
sum += cc % 10;
cc = cc / 10;
}
cc = sum;
sum = 0;
}while(cc > 9);
cout << cc << endl;
}
return 0;
}
I wonder why anyone didn't post this yet... :P
the function returns the answer :)
int Digital_root(int a) {
return a%9==0 ? 9:a%9;
}
Probably the problem is in that number might contain more than 2 digits and in this case such a modification is necessary:
int main() {
unsigned long long cc = 0;
cin >> cc;
unsigned long long sum = 0;
while (cc > 0) {
sum += cc % 10;
cc = cc / 10;
if ( sum > 9) { cc = sum; sum = 0; }
^
// cc == 0 will fail
}
cout << sum;
}
It's not perfect code, but can work
int a = 0;
int b = 0;
while (true)
{
cout << endl << "a: ";
cin >> a;
if (!a) break;
do
{
while (a)
{
b += a%10;
a /= 10;
}
a = b;
b = 0;
}
while (a > 9);
cout << endl<< "root: " << a;
The task really asks for the remainder under division by 9.
Reason: Since 10 mod 9 == 1 and thus also 10^k mod 9 == 1, the sum of decimal digits has the same remainder under division by 9 as the number itself. Repeated sums of digits do not change the remainder, so the decimal digital root of some n is the same as n mod 9 or computing the digital sum of n modulo 9.
Reducing the code of riklund to this basic task gives
#include <iostream>
#include <string>
using namespace std;
int main() {
string inStr;
while(cin >> inStr && inStr != "0") {
unsigned int cc = 0; // need only 5 bit for cc in this computation
for(string::const_iterator it = inStr.begin(); it!=inStr.end(); ++it) {
cc += *it - '0';
cc %=9;
}
cout << cc << endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
for (int i = 0; ; i++)
{
unsigned long int x,sum=0;
cin >> x;
if (x == 0)
break;
if (x <= 9)
{
sum = x;
goto z;
}
while (x > 9)
{
while (x != 0)
{
sum = sum + (x%10);
x = x / 10;
}
if (sum > 9)
{
x = sum;
sum = 0;
}
}
z:
cout << sum <<"\n";
}
}
//digital roots.cpp~KAUSHIK
#include<iostream>
using namespace std;
int sum(int n)
{
int sum=0,r;
for (;n>0;)
{
r=n%10;
sum=sum+r;
n=n/10;
}
return sum;
}
int main()
{
int n;
cout<<"enter any number"<<endl;
cin>>n;
int a=n;
n=sum(n);
if((n/10)!=0)
{
n=sum(n);
cout<<"the digital root of "<<a<<" is"<<n;
}
else cout<<"the digital root of "<<a<<" is"<<n;
return 0;
}
it works for small integers
#include <iostream>
using namespace std;
int main()
{
unsigned long long input;
while (true)
{
cin >> input;
if (input == 0) break;
input = input - (9 * ((input - 1) / 9));
cout << input << endl;
}
return 0;
}
it works simple copy that in main(), sorry for my english.
int a = 39;
int b = 0;
do
{
while (a)
{
b += a%10;
a /= 10;
}
a = b;
b = 0;
}
while (a > 9);

C decimal to binary without arrays

I think I've almost got it, but I feel like I'm go in circles trying to figure this out.
The challenge to out cout without using strings or arrays. I took the number 56 as an example and 56 should equal 111000 this is not the case as it goes through fine till 7 then the number equals number*2 + number%2 makes it equal to 15 and outputs all 1's. Idk anymore, this is driving me to the moon and back.
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
if(n%2 == 0)
{
n = n*2;
cout<<0;
}
else
{
n = n*2 + n%2;
cout<<n%2;
}
}
}
You can use the binary operator & to check if a single bit is 1 or 0.
for (int i=512; i>0; i/=2) {
cout << ( ( number & i ) != 0 ) ;
}
Note that this WILL print leading 0's.
Also, I'm assuming you only want to print positive integers.
Alternative:
for (int i=512; i>0; i/=2) {
if (number >= i) {
cout << 1;
number -= i;
} else {
count << 0;
}
}
You can use recursion
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}
This function will take the decimal, get its remainder when divided to 2. Before it the function call itself again, it checks if the decimal is less than 1(probably 0) and return to execute the printing of 1's and 0's
I had this type of problem assigned to me recently. This code example work up to a maximum of 10 binary digits (per the problem guidelines) and keep prompting for input until 0 is entered (sentinel value). This can certainly be improved but the math is correct:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
//Declare Variables
int inputValue = 0;
int workingValue = 0;
int conversionSum = 0;
//Begin Loop
do{
//Prompt for input
cout << "Enter a binary integer (0 to quit): ";
cin >> inputValue;
//Reset Variables
workingValue = inputValue;
conversionSum = 0;
//Begin processing input
//10 digits max, so 10 iterations
for (int i=0; i<10; i++) {
//Check for non-binary entry
if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
cout << "Invalid!\n";
workingValue = 0;
conversionSum = 0;
break;
}
//check to see if 2^i should be added to sum
if (workingValue%2 == 1){
conversionSum += pow(2,i);
workingValue--;
}
//divide by 10 and continue loop
workingValue= workingValue / 10;
}
//output results
cout << "converted to decimal is: " << conversionSum << endl;
}while (inputValue != 0);
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
cout << "enter a number";
int number, n, a=0;
cin >> number;
n = number;
do
{
n=n/2;
a=a+1;
}
while (n>=1);
cout << "a is" << a;
int c = a;
int b = a;
cout << "binary is";
for(int i=0; i<=c; i++)
{
int k = number / pow(2,b);
cout << k;
number = number - k * pow(2,b);
b = b-1;
}
return 0;
}
Although asked in C I have used C++. I have used the logic that if you have to convert decimal to binary we have to find the maximum power of 2 contained in the number which when added by 1 becomes the number of digit of required binary .. leftmost digit is the number of highest available power of 2 (ex in 8 highest power of 2 is 3 and 1 such is available)...then subtract this from the number and (ex 8-8=0)and search for number of next highest available power of 2 and so on.

Error "expected primary-expression before int"

I'm writing a code that will (hopefully) allow the user to input a number, and which will output the sum of the prime numbers between 2 and that number (inclusive). I'm getting one problem, however, on the penultimate line of the code. I've looked up other solutions to this question, but they don't seem to be caused by the same error as mine. Here's the code:
#include <iostream>
using namespace std;
int Q;
int sum_primes(int N) {
cout << "Enter a number and I will generate the sums of the primes up to (and including) that number: ";
cin >> Q;
int i, count, sum = 0;
for(N = 1; N <= Q; N++) {
count = 0;
for(i = 2; i <= N/2; i++) {
if (N % i == 0) {
count++;
break;
}
}
if (count == 0 && N != 1)
sum = sum + N;
return N = sum;
}
}
int main() {
cout << "The sum of these primes is: " << sum_primes(int N);
return 0;
}
cout << "..." << sum_primes(int N);
Replace int N with a number. You already defined the function, now you need to give it a parameter.
Or maybe you wanted to give N's value through user input. Then use this instead:
int N;
cin >> N;
cout << "The sum of these primes is: " << sum_primes(N);
Also, as GigaWatt pointed out, the line on which you did:
return N = sum;
is unnecessary. Simply returning sum will work just as well.
Here's the complete code:
#include <iostream>
#include <cmath>
bool isPrime(int x) {
if (x == 1) return false;
if (x == 2) return true;
bool prime = true;
for (int i = 2; i <= sqrt(x); i++) {
if (x % i == 0) { prime = false; break; }
}
return prime;
}
int sum_primes(unsigned int N) {
int sum = 0;
for ( int i = 1; i <= N; i++ ) {
if (isPrime(i)) sum += i;
}
return sum == 0 ? 1 : sum;
}
int main() {
int Q;
std::cin >> Q;
std::cout << "Sum of primes " << sum_primes(Q);
}
There are in fact multiple issues with this code. I'll list a few, but this is by no means exhaustive!
You've got some slightly crazy structuring of your code there. I guess this will become apparent when you fix the simple syntax error. Just as a point of style, I'd pass in Q as an argument to sum_primes as well as N.
You're outputting "The sum of these primes is" before asking "Enter a number".
return N = sum will exit your outer for-loop immediately. This is almost certainly not what you wanted.
I suspect you'll need to hunt down a better instroduction to C++ than you're currently working from. I'm afraid I can't offer you any advice with that.
Your argument to sum_primes is incorrect.
The function is defined to take an int, but you're not passing it one.

How do I split an int into its digits?

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.
Given the number 12345 :
5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10
I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
The following will do the trick
void splitNumber(std::list<int>& digits, int number) {
if (0 == number) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.push_front(last);
number = (number - last) / 10;
}
}
}
A simple answer to this question can be:
Read A Number "n" From The User.
Using While Loop Make Sure Its Not Zero.
Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
Then Divide The Number "n" By 10..This Removes The Last Digit of Number
"n" since in int decimal part is omitted.
Display Out The Number.
I Think It Will Help. I Used Simple Code Like:
#include <iostream>
using namespace std;
int main()
{int n,r;
cout<<"Enter Your Number:";
cin>>n;
while(n!=0)
{
r=n%10;
n=n/10;
cout<<r;
}
cout<<endl;
system("PAUSE");
return 0;
}
cast it to a string or char[] and loop on it
the classic trick is to use modulo 10:
x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)
Here's a little function to get all the digits into a vector(which is what you seem to want to do):
using namespace std;
vector<int> digits(int x){
vector<int> returnValue;
while(x>=10){
returnValue.push_back(x%10);//take digit
x=x/10; //or x/=10 if you like brevity
}
//don't forget the last digit!
returnValue.push_back(x);
return returnValue;
}
Declare an Array and store Individual digits to the array like this
int num, temp, digits = 0, s, td=1;
int d[10];
cout << "Enter the Number: ";
cin >> num;
temp = num;
do{
++digits;
temp /= 10;
} while (temp);
for (int i = 0; i < digits-1; i++)
{
td *= 10;
}
s = num;
for (int i = 0; i < digits; i++)
{
d[i] = s / td %10;
td /= 10;
}
int n = 1234;
std::string nstr = std::to_string(n);
std::cout << nstr[0]; // nstr[0] -> 1
I think this is the easiest way.
We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;
Start with the highest power of ten that fits into an int on your platform (for 32 bit int: 1.000.000.000) and perform an integer division by it. The result is the leftmost digit. Subtract this result multipled with the divisor from the original number, then continue the same game with the next lower power of ten and iterate until you reach 1.
You can just use a sequence of x/10.0f and std::floor operations to have "math approach".
Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").
I don't necessarily recommend this (it's more efficient to work with the number rather than converting it to a string), but it's easy and it works :)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>
int main()
{
int n = 23984;
std::string s = boost::lexical_cast<std::string>(n);
std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, "\n"));
return 0;
}
int n;//say 12345
string s;
scanf("%d",&n);
sprintf(s,"%5d",n);
Now you can access each digit via s[0], s[1], etc
You can count how many digits you want to print first
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int number, result, counter=0, zeros;
do{
cout << "Introduce un numero entero: ";
cin >> number;
}while (number < 0);
// We count how many digits we are going print
for(int i = number; i > 0; i = i/10)
counter++;
while(number > 0){
zeros = pow(10, counter - 1);
result = number / zeros;
number = number % zeros;
counter--;
//Muestra resultados
cout << " " << result;
}
cout<<endl;
}
Based on icecrime's answer I wrote this function
std::vector<int> intToDigits(int num_)
{
std::vector<int> ret;
string iStr = to_string(num_);
for (int i = iStr.size() - 1; i >= 0; --i)
{
int units = pow(10, i);
int digit = num_ / units % 10;
ret.push_back(digit);
}
return ret;
}
int power(int n, int b) {
int number;
number = pow(n, b);
return number;
}
void NumberOfDigits() {
int n, a;
printf("Eneter number \n");
scanf_s("%d", &n);
int i = 0;
do{
i++;
} while (n / pow(10, i) > 1);
printf("Number of digits is: \t %d \n", i);
for (int j = i-1; j >= 0; j--) {
a = n / power(10, j) % 10;
printf("%d \n", a);
}
}
int main(void) {
NumberOfDigits();
}
#include <iostream>
using namespace std;
int main()
{
int n1 ;
cout <<"Please enter five digits number: ";
cin >> n1;
cout << n1 / 10000 % 10 << " ";
cout << n1 / 1000 % 10 << " ";
cout << n1 / 100 % 10 << " ";
cout << n1 / 10 % 10 << " ";
cout << n1 % 10 << " :)";
cout << endl;
return 0;
}