Find palindrome with algorithm [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am given a number N<=200 and I need to find palindrom using ONLY this algorithm and output the palindrom and number of iterations:
1)Reverse nember
2)Revers number + previous one
Examples:
1) N=99
Out 99 0
2) N=69
69+96=165 165+561=726 726+627=1353 1353+3531=4884
Out:4884 4
My code:
#include <iostream>
using namespace std;
int rev(int a)
{
int b = 0;
while (a)
{
b = 10 * b + a % 10;
a /= 10;
}
return b;
}
int main()
{
ios::sync_with_stdio(0);
int n, c = 0;
cin >> n;
while (n != rev(n))
{
n = n + rev(n);
c++;
}
cout << n << endl << c;
return 0;
}
It works only for 70 tests out of 100:(
Can you help me so that it works for all tests?

It is simply a problem of integer overflow. A first implementation was realized with unsigned long long. It seemed to work but some overflows were not detected.
A new implementation was performed with __int128. Moreover, a signed version was used in order to be able to detect overflow easily.
Now, for n between 1 and 200, all palindromes are found, except for n = 196, for which an overflow is detected.
Here is the program:
#include <iostream>
//using namespace std;
void print128 (__int128 a) {
__int128 v64 = (__int128) 1 << 64;
__int128 high128 = a / v64;
__int128 low128 = a % v64;
unsigned long long high = high128;
unsigned long long low = low128;
if (high > 0) std::cout << high;
std::cout << low;
}
__int128 rev(__int128 a) {
__int128 b = 0;
while (a) {
b = 10 * b + a % 10;
a /= 10;
}
return b;
}
int main() {
//std::ios::sync_with_stdio(0);
int nerr = 0;
int cmax = 100000;
for (int n0 = 10; n0 <= 200; n0++) {
bool overf = false;
int c = 0;
__int128 nrev;
__int128 n = n0;
while ((n != (nrev = rev(n))) && (c < cmax)) {
if (nrev < 0) overf = true;
n = n + nrev;
if (n < 0) overf = true;
c++;
}
std::cout << "n = " << n0 << " ";;
if ((c == cmax) && !overf) {
std::cout << " ERR0R\n";
nerr++;
} else if (overf) {
std::cout << " OVERFLOW\n";
nerr++;
} else {
std::cout << " palym = ";
print128 (n);
std::cout << " c = " << c << "\n";
}
}
std::cout << "Nbre of errors = " << nerr << "\n";
return 0;
}
The question is "what to do for the 196 case ?" We don't know if a solution exists, i.e. if there is convergence. Moreover, if it converges, we don't know what the size of the palindrome could be. Trying to use int with more bits can be a long race. What is better will be to implement a dedicated int type adapted to the problem, i.e. a vector of int, each int between 0 and 9. We only have two operations to perform for this algorithm, calculating a palindrome and an addition. Calculating a palindrome will be trivial, inverse the elements of the vector (ignoring first zeros), and an addition will be rather easy to implement. Moreover, such an addition will easily detect overflow. Last but not least, the size of the vector could be adaptable for each n value, until a given limit.
EDIT: In a comment, Mark Ransom provided a link to Wikipedia page on Lychrel numbers, i.e. numbers for which the algorithm will not converge. 196 is the lowest and most famous "candidate Lychrel" number. It is conjectured, not proved, that 196 is such a number. Experiments have been performed until billions of digits, not finding a convergence for this number.

Related

(C++) Program to print all prime numbers in the a Fibonacci sequence

can someone help me out? I've been trying to get this program to print and add all prime numbers in the Fibonacci Sequence below 1000. Just typing the regular Fibonacci code works fine and will list the numbers 1 - 987.
However, the moment I put in a prime number checker it all of a sudden stops at 5 (printing "1 1 2 3 5" which is technically correct since they all fall under what a prime is (though 1 doesn't count). However I'm looking to see ALL prime numbers from 1 - 987 in the sequence, and no matter what I do I can't seem to get it to work.
My code's down below, don't mind the lack of a main function, I'm making this function as a part of a bigger program, but it can stand on its own. Currently testing it by just calling it in the main function.
#include <iostream>
using namespace std;
void primethousand() {
int fibo = 1;
int nacci = 1;
int fibonacci = 0;
int fibosum = 0; //used to get the sum of all printed numbers later, once this issue is fixed.
int pchk = 0; /*primecheck, used to check if a number is a prime or not. 1 means not prime, 0 means prime*/
cout << "\nPrime Fibonacci #s under 1000: \n\n";
for (int ctr = 1; fibonacci < 987; ctr++) {
if (ctr == 1) {
cout << fibo << " ";
continue;
} else if (ctr == 2) {
cout << nacci << " ";
continue;
}
fibonacci = fibo + nacci;
fibo = nacci;
nacci = fibonacci;
//cout << fibonacci << " ";
for (int chr = 2; chr < fibonacci; chr++) {
if (fibonacci % chr == 0) {
pchk = 1;
}
}
if (pchk == 0) {
cout << fibonacci << " ";
}
}
}
You should break up the big task into smaller tasks by using functions.
Additionally, the fibonacci sequence is growing strongly exponential. So, there are not so many numbers that can be calculated in C++ standard data types. For example, even the biggest 8 byte unsigned long long or uint64_t can hold only the 94th element of the Fibonacci series.
For Fibonaccis below 1000, it will be just 16 elements.
So, we can easily precalculate all vaues during compile time (so, not during runtime). This will be the fastest possible solution. Also the compile time will be very short. And the memory consumption will be very low.
Please see:
#include <iostream>
#include <array>
#include <cstdint>
// For fibonacci number < 1000, 16 of the series elements will be sufficient
constexpr std::size_t ArraySize{ 16 };
// Calculate all 16 needed fibonacci number during compile time
consteval auto CreateFibonacciNumberArray() {
std::array<std::uint64_t, ArraySize> fs{ 1, 1 };
for (std::size_t i{ 2 }; i < ArraySize; ++i)
fs[i] = fs[i - 1] + fs[i - 2];
return fs;
}
// This is an array with the 16 fibonacci numbers. It is an compile time array
constexpr auto FIB = CreateFibonacciNumberArray();
// Compiletime function to calculate, if fibonacci numbers are prime
constexpr bool isPrime(const std::uint64_t number) {
if (number % 2 == 0 or number <= 2) return false;
for (std::uint64_t i = 3; (i * i) <= number; i += 2)
if (number % i == 0) return false;
return true;
}
// Create a compile time array, to indicate, if a fibnacci number is prinme
consteval auto IsPrime(const std::array<std::uint64_t, ArraySize>& FIB) {
std::array<bool, ArraySize> primeFibonacci{};
for (std::size_t i{}; i < ArraySize; ++i)
primeFibonacci[i] = isPrime(FIB[i]);
return primeFibonacci;
}
// Boolean compile time array that shows, if a fibonacci number is prime
constexpr auto FibIsPrime = IsPrime(FIB);
int main()
{
for (std::size_t i{}; i < ArraySize; ++i) {
std::cout << FIB[i];
if (FibIsPrime[i]) std::cout << "\tis prime";
std::cout << '\n';
}
}
It looks like once pchk is set to 1, you never set it back to zero, so further primes are never noticed..

Find One to N is Prime optimization

So I was inspired by a recent Youtube video from the Numberphile Channel. This one to be exact. Cut to around the 5 minute mark for the exact question or example that I am referring to.
TLDR; A number is created with all the digits corresponding to 1 to N. Example: 1 to 10 is the number 12,345,678,910. Find out if this number is prime. According to the video, N has been checked up to 1,000,000.
From the code below, I have taken the liberty of starting this process at 1,000,000 and only going to 10,000,000. I'm hoping to increase this to a larger number later.
So my question or the assistance that I need is optimization for this problem. I'm sure each number will still take very long to check but even a minimal percentage of optimization would go a long way.
Edit 1: Optimize which division numbers are used. Ideally this divisionNumber would only be prime numbers.
Here is the code:
#include <iostream>
#include <chrono>
#include <ctime>
namespace
{
int myPow(int x, int p)
{
if (p == 0) return 1;
if (p == 1) return x;
if (p == 2) return x * x;
int tmp = myPow(x, p / 2);
if (p % 2 == 0) return tmp * tmp;
else return x * tmp * tmp;
}
int getNumDigits(unsigned int num)
{
int count = 0;
while (num != 0)
{
num /= 10;
++count;
}
return count;
}
unsigned int getDigit(unsigned int num, int position)
{
int digit = num % myPow(10, getNumDigits(num) - (position - 1));
return digit / myPow(10, getNumDigits(num) - position);
}
unsigned int getTotalDigits(int num)
{
unsigned int total = 0;
for (int i = 1; i <= num; i++)
total += getNumDigits(i);
return total;
}
// Returns the 'index'th digit of number created from 1 to num
int getIndexDigit(int num, int index)
{
if (index <= 9)
return index;
for (int i = 10; i <= num; i++)
{
if (getTotalDigits(i) >= index)
return getDigit(i, getNumDigits(i) - (getTotalDigits(i) - index));
}
}
// Can this be optimized?
int floorSqrt(int x)
{
if (x == 0 || x == 1)
return x;
int i = 1, result = 1;
while (result <= x)
{
i++;
result = i * i;
}
return i - 1;
}
void PrintTime(double num, int i)
{
constexpr double SECONDS_IN_HOUR = 3600;
constexpr double SECONDS_IN_MINUTE = 60;
double totalSeconds = num;
int hours = totalSeconds / SECONDS_IN_HOUR;
int minutes = (totalSeconds - (hours * SECONDS_IN_HOUR)) / SECONDS_IN_MINUTE;
int seconds = totalSeconds - (hours * SECONDS_IN_HOUR) - (minutes * SECONDS_IN_MINUTE);
std::cout << "Elapsed time for " << i << ": " << hours << "h, " << minutes << "m, " << seconds << "s\n";
}
}
int main()
{
constexpr unsigned int MAX_NUM_CHECK = 10000000;
for (int i = 1000000; i <= MAX_NUM_CHECK; i++)
{
auto start = std::chrono::system_clock::now();
int digitIndex = 1;
// Simplifying this to move to the next i in the loop early:
// if i % 2 then the last digit is a 0, 2, 4, 6, or 8 and is therefore divisible by 2
// if i % 5 then the last digit is 0 or 5 and is therefore divisible by 5
if (i % 2 == 0 || i % 5 == 0)
{
std::cout << i << " not prime" << '\n';
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
PrintTime(elapsed_seconds.count(), i);
continue;
}
bool isPrime = true;
int divisionNumber = 3;
int floorNum = floorSqrt(i);
while (divisionNumber <= floorNum && isPrime)
{
if (divisionNumber % 5 == 0)
{
divisionNumber += 2;
continue;
}
int number = 0;
int totalDigits = getTotalDigits(i);
// This section does the division necessary to iterate through each digit of the 1 to N number
// Example: Think of dividing 124 into 123456 on paper and how you would iterate through that process
while (digitIndex <= totalDigits)
{
number *= 10;
number += getIndexDigit(i, digitIndex);
number %= divisionNumber;
digitIndex++;
}
if (number == 0)
{
isPrime = false;
break;
}
divisionNumber += 2;
}
if (isPrime)
std::cout << "N = " << i << " is prime." << '\n';
else
std::cout << i << " not prime" << '\n';
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
PrintTime(elapsed_seconds.count(), i);
}
}
Its nice to see you are working on the same question I pondered few months ago.
Please refer to question posted in Math Stackexchange for better resources.
TL-DR,
The number you are looking for is called SmarandachePrime.
As per your code, it seems you are dividing with every number that is not a multiple of 2,5. To optimize you can actually check for n = 6k+1 ( 𝑘 ∈ ℕ ).
unfortunately, it is still not a better approach with respect to the number you are dealing with.
The better approach is to use primality test screening to find probable prime numbers in the sequence and then check whether they are prime or not. These tests take a less time ~(O(k log3n)) to check whether a number is prime or not, using mathematical fundamentals, compared to division.
there are several libraries that provide functions for primality check.
for python, you can use gmpy2 library, which uses Miller-Rabin Primality test to find probable primes.
I recommend you to further read about different Primality tests here.
I believe you are missing one very important check, and it's the division by 3:
A number can be divided by 3 is the sum of the numbers can be divided by 3, and your number consists of all numbers from 1 to N.
The sum of all numbers from 1 to N equals:
N * (N+1) / 2
This means that, if N or N+1 can be divided by 3, then your number cannot be prime.
So before you do anything, check MOD(N,3) and MOD(N+1,3). If either one of them equals zero, you can't have a prime number.

C++ [Recursive] Write a number as sum of ascending powers of 2 [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 5 years ago.
Improve this question
So as the title says,I have to write a number as sum of ascending powers of 2.
For instance, if I input 10, 25 , 173
10 = 2 + 8
25 = 1 + 8 + 16
173 = 1 + 4 + 8 + 32 + 128
So this is what I have done:
#include <iostream>
using namespace std;
int x,c;
int v[500];
void Rezolva(int putere)
{
if(putere * 2 <= x)
Rezolva(putere * 2);
if(x - putere >= 0)
{
c++;
v[c] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c; i >= 1; i--)
cout << v[i] << " ";
return 0;
}
I have a program which gives my code some tests and verifies if it's correct. To one test, it says that I exit the array. Is there any way to get rid of the array or to fix this problem ? If I didn't use the array it would have been in descending order.
The error isn't a compiler error.
Caught fatal signal 11 is what I receive when my program checks some tests on the code
For values higher than 10^9 the program crashes so you need to change from int to long long.
#include <iostream>
using namespace std;
long long x,c;
long long v[500];
void Rezolva(long long putere)
{
if (putere * 2 <= x)
Rezolva(putere * 2);
if (x - putere >= 0)
{
v[c++] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c - 1; i >= 0; i--)
cout << v[i] << " ";
return 0;
}
All in all, a simple overflow was the cause.
It was a simple overflow. And by the way a way easier way to do it is have a long long unsigned int
#include <bitset>
unsigned long long x = input;
std::cout << x << " = ";
std::string str = std::bitset<64>(x).to_string();
for (int i = str.size()-1; i >= 0; --i)
if(str[i]-'0')
std::cout << (2ull << i) << " + ";
if (x)
std::cout << char(8)<<char(8) << std::endl; //DELETING LAST "+" for non-zero x
else
std::cout << "0\n";
If you have a fixed size integer (e.g. int etc.) then you can just start at the greatest possible power of two, and if your number is bigger than that power, subtract the power of 2. Then go to the next power of two.
This is similar to how you would normally write numbers yourself starting from the most significant digit. So also works for how numbers are printed in base 16 (hex), 10, binary literals, etc.
int main() {
unsigned x = 173;
std::cout << x << " = ";
bool first = true;
// get the max power from a proper constant
for (unsigned power = 0x80000000; power > 0; power >>= 1)
{
if (power <= x)
{
if (!first) std::cout << " + ";
std::cout << power;
x -= power;
first = false;
}
}
assert(x == 0);
std::cout << std::endl;
}
Outputs:
173 = 128 + 32 + 8 + 4 + 1

C++ - Decimal to binary converting

I wrote a 'simple' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there's a lot simpler way so can you show me?
Here's the code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
system("clear");
cout << "Enter a decimal number: ";
cin >> a1;
a2 = a1; //we need our number for later on so we save it in another variable
while (a1!=0) //dividing by two until we hit 0
{
remainder = a1%2; //getting a remainder - decimal number(1 or 0)
a1 = a1/2; //dividing our number by two
maxtab++; //+1 to max elements of the table
}
maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
a1 = a2; //we must do calculations one more time so we're gatting back our original number
table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)
while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
{
remainder = a1%2; //getting a remainder
a1 = a1/2; //dividing by 2
table[tab] = remainder; //adding 0 or 1 to an element
tab++; //tab (element count) increases by 1 so next remainder is saved in another element
}
tab--; //same as with maxtab--
cout << "Your binary number: ";
while (tab>=0) //until we get to the 0 (1st) element of the table
{
cout << table[tab] << " "; //write the value of an element (0 or 1)
tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
}
cout << endl;
return 0;
}
By the way it's complicated but I tried my best.
edit - Here is the solution I ended up using:
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
std::bitset has a .to_string() method that returns a std::string holding a text representation in binary, with leading-zero padding.
Choose the width of the bitset as needed for your data, e.g. std::bitset<32> to get 32-character strings from 32-bit integers.
#include <iostream>
#include <bitset>
int main()
{
std::string binary = std::bitset<8>(128).to_string(); //to binary
std::cout<<binary<<"\n";
unsigned long decimal = std::bitset<8>(binary).to_ulong();
std::cout<<decimal<<"\n";
return 0;
}
EDIT: Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.
The following is a recursive function which takes a positive integer and prints its binary digits to the console.
Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.
/**
* Takes a unsigned integer, converts it into binary and prints it to the console.
* #param n the number to convert and print
*/
void convertToBinary(unsigned int n)
{
if (n / 2 != 0) {
convertToBinary(n / 2);
}
printf("%d", n % 2);
}
Credits to UoA ENGGEN 131
*Note: The benefit of using an unsigned int is that it can't be negative.
You can use std::bitset to convert a number to its binary format.
Use the following code snippet:
std::string binary = std::bitset<8>(n).to_string();
I found this on stackoverflow itself. I am attaching the link.
A pretty straight forward solution to print binary:
#include <iostream>
using namespace std;
int main()
{
int num,arr[64];
cin>>num;
int i=0,r;
while(num!=0)
{
r = num%2;
arr[i++] = r;
num /= 2;
}
for(int j=i-1;j>=0;j--){
cout<<arr[j];
}
}
Non recursive solution:
#include <iostream>
#include<string>
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
int main()
{
std::string i= toBinary(10);
std::cout<<i;
}
Recursive solution:
#include <iostream>
#include<string>
std::string r="";
std::string toBinary(int n)
{
r=(n%2==0 ?"0":"1")+r;
if (n / 2 != 0) {
toBinary(n / 2);
}
return r;
}
int main()
{
std::string i=toBinary(10);
std::cout<<i;
}
An int variable is not in decimal, it's in binary. What you're looking for is a binary string representation of the number, which you can get by applying a mask that filters individual bits, and then printing them:
for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
cout << value & (1 << i) ? '1' : '0';
That's the solution if your question is algorithmic. If not, you should use the std::bitset class to handle this for you:
bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
Here are two approaches. The one is similar to your approach
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
const unsigned long long base = 2;
std::string s;
s.reserve( std::numeric_limits<unsigned long long>::digits );
do { s.push_back( x % base + '0' ); } while ( x /= base );
std::cout << std::string( s.rbegin(), s.rend() ) << std::endl;
}
}
and the other uses std::bitset as others suggested.
#include <iostream>
#include <string>
#include <bitset>
#include <limits>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
std::string s =
std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();
std::string::size_type n = s.find( '1' );
std::cout << s.substr( n ) << std::endl;
}
}
The conversion from natural number to a binary string:
string toBinary(int n) {
if (n==0) return "0";
else if (n==1) return "1";
else if (n%2 == 0) return toBinary(n/2) + "0";
else if (n%2 != 0) return toBinary(n/2) + "1";
}
For this , In C++ you can use itoa() function .This function convert any Decimal integer to binary, decimal , hexadecimal and octal number.
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
char res[1000];
cin>>a;
itoa(a,res,10);
cout<<"Decimal- "<<res<<endl;
itoa(a,res,2);
cout<<"Binary- "<<res<<endl;
itoa(a,res,16);
cout<<"Hexadecimal- "<<res<<endl;
itoa(a,res,8);
cout<<"Octal- "<<res<<endl;return 0;
}
However, it is only supported by specific compilers.
You can see also: itoa - C++ Reference
Here is modern variant that can be used for ints of different sizes.
#include <type_traits>
#include <bitset>
template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
return std::bitset<sizeof(T) * 8>(i).to_string();
}
Your solution needs a modification. The final string should be reversed before returning:
std::reverse(r.begin(), r.end());
return r;
DECIMAL TO BINARY NO ARRAYS USED *made by Oya:
I'm still a beginner, so this code will only use loops and variables xD...
Hope you like it. This can probably be made simpler than it is...
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int i;
int expoentes; //the sequence > pow(2,i) or 2^i
int decimal;
int extra; //this will be used to add some 0s between the 1s
int x = 1;
cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
cout << "\n\nWARNING: Only works until ~1.073 millions\n";
cout << " To exit, enter a negative number\n\n";
while(decimal >= 0){
cout << "\n----- // -----\n\n";
cin >> decimal;
cout << "\n";
if(decimal == 0){
cout << "0";
}
while(decimal >= 1){
i = 0;
expoentes = 1;
while(decimal >= expoentes){
i++;
expoentes = pow(2,i);
}
x = 1;
cout << "1";
decimal -= pow(2,i-x);
extra = pow(2,i-1-x);
while(decimal < extra){
cout << "0";
x++;
extra = pow(2,i-1-x);
}
}
}
return 0;
}
here a simple converter by using std::string as container. it allows a negative value.
#include <iostream>
#include <string>
#include <limits>
int main()
{
int x = -14;
int n = std::numeric_limits<int>::digits - 1;
std::string s;
s.reserve(n + 1);
do
s.push_back(((x >> n) & 1) + '0');
while(--n > -1);
std::cout << s << '\n';
}
This is a more simple program than ever
//Program to convert Decimal into Binary
#include<iostream>
using namespace std;
int main()
{
long int dec;
int rem,i,j,bin[100],count=-1;
again:
cout<<"ENTER THE DECIMAL NUMBER:- ";
cin>>dec;//input of Decimal
if(dec<0)
{
cout<<"PLEASE ENTER A POSITIVE DECIMAL";
goto again;
}
else
{
cout<<"\nIT's BINARY FORM IS:- ";
for(i=0;dec!=0;i++)//making array of binary, but reversed
{
rem=dec%2;
bin[i]=rem;
dec=dec/2;
count++;
}
for(j=count;j>=0;j--)//reversed binary is printed in correct order
{
cout<<bin[j];
}
}
return 0;
}
There is in fact a very simple way to do so. What we do is using a recursive function which is given the number (int) in the parameter. It is pretty easy to understand. You can add other conditions/variations too. Here is the code:
int binary(int num)
{
int rem;
if (num <= 1)
{
cout << num;
return num;
}
rem = num % 2;
binary(num / 2);
cout << rem;
return rem;
}
// function to convert decimal to binary
void decToBinary(int n)
{
// array to store binary number
int binaryNum[1000];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
refer :-
https://www.geeksforgeeks.org/program-decimal-binary-conversion/
or
using function :-
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
cout<<bitset<8>(n).to_string()<<endl;
}
or
using left shift
#include<bits/stdc++.h>
using namespace std;
int main()
{
// here n is the number of bit representation we want
int n;cin>>n;
// num is a number whose binary representation we want
int num;
cin>>num;
for(int i=n-1;i>=0;i--)
{
if( num & ( 1 << i ) ) cout<<1;
else cout<<0;
}
}
#include <iostream>
#include <bitset>
#define bits(x) (std::string( \
std::bitset<8>(x).to_string<char,std::string::traits_type, std::string::allocator_type>() ).c_str() )
int main() {
std::cout << bits( -86 >> 1 ) << ": " << (-86 >> 1) << std::endl;
return 0;
}
Okay.. I might be a bit new to C++, but I feel the above examples don't quite get the job done right.
Here's my take on this situation.
char* DecimalToBinary(unsigned __int64 value, int bit_precision)
{
int length = (bit_precision + 7) >> 3 << 3;
static char* binary = new char[1 + length];
int begin = length - bit_precision;
unsigned __int64 bit_value = 1;
for (int n = length; --n >= begin; )
{
binary[n] = 48 | ((value & bit_value) == bit_value);
bit_value <<= 1;
}
for (int n = begin; --n >= 0; )
binary[n] = 48;
binary[length] = 0;
return binary;
}
#value = The Value we are checking.
#bit_precision = The highest left most bit to check for.
#Length = The Maximum Byte Block Size. E.g. 7 = 1 Byte and 9 = 2 Byte, but we represent this in form of bits so 1 Byte = 8 Bits.
#binary = just some dumb name I gave to call the array of chars we are setting. We set this to static so it won't be recreated with every call. For simply getting a result and display it then this works good, but if let's say you wanted to display multiple results on a UI they would all show up as the last result. This can be fixed by removing static, but make sure you delete [] the results when you are done with it.
#begin = This is the lowest index that we are checking. Everything beyond this point is ignored. Or as shown in 2nd loop set to 0.
#first loop - Here we set the value to 48 and basically add a 0 or 1 to 48 based on the bool value of (value & bit_value) == bit_value. If this is true the char is set to 49. If this is false the char is set to 48. Then we shift the bit_value or basically multiply it by 2.
#second loop - Here we set all the indexes we ignored to 48 or '0'.
SOME EXAMPLE OUTPUTS!!!
int main()
{
int val = -1;
std::cout << DecimalToBinary(val, 1) << '\n';
std::cout << DecimalToBinary(val, 3) << '\n';
std::cout << DecimalToBinary(val, 7) << '\n';
std::cout << DecimalToBinary(val, 33) << '\n';
std::cout << DecimalToBinary(val, 64) << '\n';
std::cout << "\nPress any key to continue. . .";
std::cin.ignore();
return 0;
}
00000001 //Value = 2^1 - 1
00000111 //Value = 2^3 - 1.
01111111 //Value = 2^7 - 1.
0000000111111111111111111111111111111111 //Value = 2^33 - 1.
1111111111111111111111111111111111111111111111111111111111111111 //Value = 2^64 - 1.
SPEED TESTS
Original Question's Answer: "Method: toBinary(int);"
Executions: 10,000 , Total Time (Milli): 4701.15 , Average Time (Nanoseconds): 470114
My Version: "Method: DecimalToBinary(int, int);"
//Using 64 Bit Precision.
Executions: 10,000,000 , Total Time (Milli): 3386 , Average Time (Nanoseconds): 338
//Using 1 Bit Precision.
Executions: 10,000,000, Total Time (Milli): 634, Average Time (Nanoseconds): 63
Below is simple C code that converts binary to decimal and back again. I wrote it long ago for a project in which the target was an embedded processor and the development tools had a stdlib that was way too big for the firmware ROM.
This is generic C code that does not use any library, nor does it use division or the remainder (%) operator (which is slow on some embedded processors), nor does it use any floating point, nor does it use any table lookup nor emulate any BCD arithmetic. What it does make use of is the type long long, more specifically unsigned long long (or uint64_t), so if your embedded processor (and the C compiler that goes with it) cannot do 64-bit integer arithmetic, this code is not for your application. Otherwise, I think this is production quality C code (maybe after changing long to int32_t and unsigned long long to uint64_t). I have run this overnight to test it for every 2³² signed integer values and there is no error in conversion in either direction.
We had a C compiler/linker that could generate executables and we needed to do what we could do without any stdlib (which was a pig). So no printf() nor scanf(). Not even an sprintf() nor sscanf(). But we still had a user interface and had to convert base-10 numbers into binary and back. (We also made up our own malloc()-like utility also and our own transcendental math functions too.)
So this was how I did it (the main program and calls to stdlib were there for testing this thing on my mac, not for the embedded code). Also, because some older dev systems don't recognize "int64_t" and "uint64_t" and similar types, the types long long and unsigned long long are used and assumed to be the same. And long is assumed to be 32 bits. I guess I could have typedefed it.
// returns an error code, 0 if no error,
// -1 if too big, -2 for other formatting errors
int decimal_to_binary(char *dec, long *bin)
{
int i = 0;
int past_leading_space = 0;
while (i <= 64 && !past_leading_space) // first get past leading spaces
{
if (dec[i] == ' ')
{
i++;
}
else
{
past_leading_space = 1;
}
}
if (!past_leading_space)
{
return -2; // 64 leading spaces does not a number make
}
// at this point the only legitimate remaining
// chars are decimal digits or a leading plus or minus sign
int negative = 0;
if (dec[i] == '-')
{
negative = 1;
i++;
}
else if (dec[i] == '+')
{
i++; // do nothing but go on to next char
}
// now the only legitimate chars are decimal digits
if (dec[i] == '\0')
{
return -2; // there needs to be at least one good
} // digit before terminating string
unsigned long abs_bin = 0;
while (i <= 64 && dec[i] != '\0')
{
if ( dec[i] >= '0' && dec[i] <= '9' )
{
if (abs_bin > 214748364)
{
return -1; // this is going to be too big
}
abs_bin *= 10; // previous value gets bumped to the left one digit...
abs_bin += (unsigned long)(dec[i] - '0'); // ... and a new digit appended to the right
i++;
}
else
{
return -2; // not a legit digit in text string
}
}
if (dec[i] != '\0')
{
return -2; // not terminated string in 64 chars
}
if (negative)
{
if (abs_bin > 2147483648)
{
return -1; // too big
}
*bin = -(long)abs_bin;
}
else
{
if (abs_bin > 2147483647)
{
return -1; // too big
}
*bin = (long)abs_bin;
}
return 0;
}
void binary_to_decimal(char *dec, long bin)
{
unsigned long long acc; // 64-bit unsigned integer
if (bin < 0)
{
*(dec++) = '-'; // leading minus sign
bin = -bin; // make bin value positive
}
acc = 989312855LL*(unsigned long)bin; // very nearly 0.2303423488 * 2^32
acc += 0x00000000FFFFFFFFLL; // we need to round up
acc >>= 32;
acc += 57646075LL*(unsigned long)bin;
// (2^59)/(10^10) = 57646075.2303423488 = 57646075 + (989312854.979825)/(2^32)
int past_leading_zeros = 0;
for (int i=9; i>=0; i--) // maximum number of digits is 10
{
acc <<= 1;
acc += (acc<<2); // an efficient way to multiply a long long by 10
// acc *= 10;
unsigned int digit = (unsigned int)(acc >> 59); // the digit we want is in bits 59 - 62
if (digit > 0)
{
past_leading_zeros = 1;
}
if (past_leading_zeros)
{
*(dec++) = '0' + digit;
}
acc &= 0x07FFFFFFFFFFFFFFLL; // mask off this digit and go on to the next digit
}
if (!past_leading_zeros) // if all digits are zero ...
{
*(dec++) = '0'; // ... put in at least one zero digit
}
*dec = '\0'; // terminate string
}
#if 1
#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
{
char dec[64];
long bin, result1, result2;
unsigned long num_errors;
long long long_long_bin;
num_errors = 0;
for (long_long_bin=-2147483648LL; long_long_bin<=2147483647LL; long_long_bin++)
{
bin = (long)long_long_bin;
if ((bin&0x00FFFFFFL) == 0)
{
printf("bin = %ld \n", bin); // this is to tell us that things are moving along
}
binary_to_decimal(dec, bin);
decimal_to_binary(dec, &result1);
sscanf(dec, "%ld", &result2); // decimal_to_binary() should do the same as this sscanf()
if (bin != result1 || bin != result2)
{
num_errors++;
printf("bin = %ld, result1 = %ld, result2 = %ld, num_errors = %ld, dec = %s \n",
bin, result1, result2, num_errors, dec);
}
}
printf("num_errors = %ld \n", num_errors);
return 0;
}
#else
#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
{
char dec[64];
long bin;
printf("bin = ");
scanf("%ld", &bin);
while (bin != 0)
{
binary_to_decimal(dec, bin);
printf("dec = %s \n", dec);
printf("bin = ");
scanf("%ld", &bin);
}
return 0;
}
#endif
My way of converting decimal to binary in C++. But since we are using mod, this function will work in case of hexadecimal or octal also. You can also specify bits. This function keeps calculating the lowest significant bit and place it on the end of the string. If you are not so similar to this method than you can vist: https://www.wikihow.com/Convert-from-Decimal-to-Binary
#include <bits/stdc++.h>
using namespace std;
string itob(int bits, int n) {
int count;
char str[bits + 1]; // +1 to append NULL character.
str[bits] = '\0'; // The NULL character in a character array flags the end
// of the string, not appending it may cause problems.
count = bits - 1; // If the length of a string is n, than the index of the
// last character of the string will be n - 1. Cause the
// index is 0 based not 1 based. Try yourself.
do {
if (n % 2)
str[count] = '1';
else
str[count] = '0';
n /= 2;
count--;
} while (n > 0);
while (count > -1) {
str[count] = '0';
count--;
}
return str;
}
int main() {
cout << itob(1, 0) << endl; // 0 in 1 bit binary.
cout << itob(2, 1) << endl; // 1 in 2 bit binary.
cout << itob(3, 2) << endl; // 2 in 3 bit binary.
cout << itob(4, 4) << endl; // 4 in 4 bit binary.
cout << itob(5, 15) << endl; // 15 in 5 bit binary.
cout << itob(6, 30) << endl; // 30 in 6 bit binary.
cout << itob(7, 61) << endl; // 61 in 7 bit binary.
cout << itob(8, 127) << endl; // 127 in 8 bit binary.
return 0;
}
The Output:
0
01
010
0100
01111
011110
0111101
01111111
Since you asked for a simple way, I am sharing this answer, after 8 years
Here is the expression!
Is it not interesting when there is no if condition, and we can get 0 or 1 with just a simple expression?
Well yes, NO if, NO long division
Here is what each variable means
Note: variable is the orange highlighted ones
Number: 0-infinity (a value to be converted to binary)
binary holder: 1 / 2 / 4 / 8 / 16 / 32 / ... (Place of binary needed, just like tens, hundreds)
Result: 0 or 1
If you want to make binary holder from 1 / 2 / 4 / 8 / 16 /... to 1 / 2 / 3 / 4 / 5/...
then use this expression
The procedure is simple for the second expression
First, the number variable is always, your number needed, and its stable.
Second the binary holder variable needs to be changed ,in a for loop, by +1 for the second image, x2 for the first image
I don't know c++ a lot ,here is a js code,for your understanding
function FindBinary(Number) {
var x,i,BinaryValue = "",binaryHolder = 1;
for (i = 1; Math.pow(2, i) <= Number; i++) {}//for trimming, you can even remove this and set i to 7,see the result
for (x = 1; x <= i; x++) {
var Algorithm = ((Number - (Number % binaryHolder)) / binaryHolder) % 2;//Main algorithm
BinaryValue = Algorithm + BinaryValue;
binaryHolder += binaryHolder;
}
return BinaryValue;
}
console.log(FindBinary(17));//your number
more ever, I think language doesn't matters a lot for algorithm questions
You want to do something like:
cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int main() {
// Initialize Variables
double x;
int xOct;
int xHex;
//Initialize a variable that stores the order if the numbers in binary/sexagesimal base
vector<int> rem;
//Get Demical value
cout << "Number (demical base): ";
cin >> x;
//Set the variables
xOct = x;
xHex = x;
//Get the binary value
for (int i = 0; x >= 1; i++) {
rem.push_back(abs(remainder(x, 2)));
x = floor(x / 2);
}
//Print binary value
cout << "Binary: ";
int n = rem.size();
while (n > 0) {
n--;
cout << rem[n];
} cout << endl;
//Print octal base
cout << oct << "Octal: " << xOct << endl;
//Print hexademical base
cout << hex << "Hexademical: " << xHex << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin>>a;
for(int i=31;i>=0;i--)
{
b=(a>>i)&1;
cout<<b;
}
}
HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY
#include<iostream>
using namespace std;
int main()
{
int input,rem,res,count=0,i=0;
cout<<"Input number: ";
cin>>input;`enter code here`
int num=input;
while(input > 0)
{
input=input/2;
count++;
}
int arr[count];
while(num > 0)
{
arr[i]=num%2;
num=num/2;
i++;
}
for(int i=count-1 ; i>=0 ; i--)
{
cout<<" " << arr[i]<<" ";
}
return 0;
}
#include <iostream>
// x is our number to test
// pow is a power of 2 (e.g. 128, 64, 32, etc...)
int printandDecrementBit(int x, int pow)
{
// Test whether our x is greater than some power of 2 and print the bit
if (x >= pow)
{
std::cout << "1";
// If x is greater than our power of 2, subtract the power of 2
return x - pow;
}
else
{
std::cout << "0";
return x;
}
}
int main()
{
std::cout << "Enter an integer between 0 and 255: ";
int x;
std::cin >> x;
x = printandDecrementBit(x, 128);
x = printandDecrementBit(x, 64);
x = printandDecrementBit(x, 32);
x = printandDecrementBit(x, 16);
std::cout << " ";
x = printandDecrementBit(x, 8);
x = printandDecrementBit(x, 4);
x = printandDecrementBit(x, 2);
x = printandDecrementBit(x, 1);
return 0;
}
this is a simple way to get the binary form of an int. credit to learncpp.com. im sure this could be used in different ways to get to the same point.
In this approach, the decimal will be converted to the respective binary number in the string formate. The string return type is chosen since it can handle more range of input values.
class Solution {
public:
string ConvertToBinary(int num)
{
vector<int> bin;
string op;
for (int i = 0; num > 0; i++)
{
bin.push_back(num % 2);
num /= 2;
}
reverse(bin.begin(), bin.end());
for (size_t i = 0; i < bin.size(); ++i)
{
op += to_string(bin[i]);
}
return op;
}
};
using bitmask and bitwise and .
string int2bin(int n){
string x;
for(int i=0;i<32;i++){
if(n&1) {x+='1';}
else {x+='0';}
n>>=1;
}
reverse(x.begin(),x.end());
return x;
}
You Could use std::bitset:
#include <bits/stdc++.h>
int main()
{
std::string binary = std::bitset<(int)ceil(log2(10))>(10).to_string(); // decimal number is 10
std::cout << binary << std::endl; // 1010
return 0;
}
SOLUTION 1
Shortest function. Recursive. No headers required.
size_t bin(int i) {return i<2?i:10*bin(i/2)+i%2;}
The simplicity of this function comes at the cost of some limitations. It returns correct values only for arguments between 0 and 1048575 (2 to the power of how many digits the largest unsigned int has, -1). I used the following program to test it:
#include <iostream> // std::cout, std::cin
#include <climits> // ULLONG_MAX
#include <math.h> // pow()
int main()
{
size_t bin(int);
int digits(size_t);
int i = digits(ULLONG_MAX); // maximum digits of the return value of bin()
int iMax = pow(2.0,i)-1; // maximum value of a valid argument of bin()
while(true) {
std::cout << "Decimal: ";
std::cin >> i;
if (i<0 or i>iMax) {
std::cout << "\nB Integer out of range, 12:1";
return 0;
}
std::cout << "Binary: " << bin(i) << "\n\n";
}
return 0;
}
size_t bin(int i) {return i<2?i:10*bin(i/2)+i%2;}
int digits(size_t i) {return i<10?1:digits(i/10)+1;}
SOLUTION 2
Short. Recursive. Some headers required.
std::string bin(size_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}
This function can return the binary representation of the largest integers as a string. I used the following program to test it:
#include <string> // std::string
#include <iostream> // std::cout, std::cin
int main()
{
std::string s, bin(size_t);
size_t i, x;
std::cout << "Enter exit code: "; // Used to exit the program.
std::cin >> x;
while(i!=x) {
std::cout << "\nDecimal: ";
std::cin >> i;
std::cout << "Binary: " << bin(i) << "\n";
}
return 0;
}
std::string bin(size_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}

Square root of a number... Accurate up to n precision [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I could not understand the above method. Can someone please explain? I have done some code but its is limited to some hard coded precision and seems to consume too much resource of computer.
R = 0.00001
INPUT N
WHILE R*R != N
R = R + 0.00001
ENDWHILE
PRINT R
What is the Algorithm or C++ code for square root of a number upto n precision?
n can be taken from user if required.
There are algorithms that are much better suited to computer evaluation. I learned the one in the question in the 1960's, as a way of manually calculating a square root digit-by-digit using a process rather like long division.
The objective, during calculation of the nth digit of the result, is to find the largest prefix string such that the square is less than or equal to the first 2n digits of the input.
The key underlying idea is that (a+b)^2 = a^2 + b^2 + 2ab. In the algorithm, a is the partial result so far, and b is the new digit. It accounts for factors of 100 in the square and 10 in the root by moving two places in the input for one generated digit in the result.
Let p be the partial result before appending digit d. We have already subtracted p^2 from the input. We need to also subtract d^2 + 2pd, to maintain subtraction of the square of the new partial result. Equivalently, subtract d(2p+d). We keep p already doubled, append d, and multiply by d. Before going on to the next step, we need to double d as well.
Here is a piece of C++ code, although it is not arbitrary precision, it may be useful to you. It is a little closer to a complete solution then your BASIC code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <climits>
const unsigned g_unPlaces = 8;
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "USAGE: " << *argv << " NUMBER" << std::endl;
return 1;
}
std::vector<unsigned> vecInteger;
std::vector<unsigned> vecDecimal;
char *pDecimal = strchr(argv[1], '.');
// Read integer part of NUMBER
if (pDecimal == NULL) pDecimal = argv[1] + strlen(argv[1]);
if ((pDecimal - argv[1]) % 2) vecInteger.push_back(0);
for (char *pCurrent = argv[1]; pCurrent < pDecimal; ++pCurrent)
{
int nValue = *pCurrent - '0';
if (nValue >= 10 || nValue < 0)
{
std::cerr << "Error: Invalid character in input!" << std::endl;
return 1;
}
vecInteger.push_back((unsigned) nValue);
}
// Read decimal part of NUMBER
if (*pDecimal != '\0')
{
for (++pDecimal; *pDecimal != '\0'; ++pDecimal)
{
if (*pDecimal == '.')
{
std::cerr << "Error: Multiple decimals in input!" << std::endl;
return 1;
}
int nValue = *pDecimal - '0';
if (nValue >= 10 || nValue < 0)
{
std::cerr << "Error: Invalid character in input!" << std::endl;
return 1;
}
vecDecimal.push_back((unsigned) nValue);
}
if (vecDecimal.size() % 2) vecDecimal.push_back(0);
}
const unsigned unInteger = vecInteger.size();
const unsigned unDecimal = vecDecimal.size();
std::vector<unsigned> vecValues;
unsigned x, y = 0, c = 0, p = 0;
for (unsigned i = 0; i < g_unPlaces; ++i)
{
if (2*i < unInteger-1)
{
c = (c*100 - y*100) + vecInteger[i*2]*10 + vecInteger[i*2+1];
}
else if (2*i < unInteger+unDecimal-1)
{
c = (c*100 - y*100) + vecDecimal[i*2-unInteger]*10
+ vecDecimal[i*2+1-unInteger];
}
else
{
c = c*100 - y*100;
}
if (c == 0) break;
y = 0;
for (x = 1; x < 10; ++x)
{
unsigned temp = x*(20*p + x);
if (temp > c) { --x; break; }
y = temp;
}
p = 10*p + x;
vecValues.push_back(x);
}
// Write the result
for (unsigned i = 0; i < unInteger/2; ++i)
{
std::cout << vecValues[i];
}
std::cout << '.';
for (unsigned i = unInteger/2; i < vecValues.size(); ++i)
{
std::cout << vecValues[i];
}
std::cout << std::endl;
return 0;
}
As for help in understanding your algorithm, the best approach is to begin at the begging and work through each step. Try with small values like 4, 16 and 64. Go through the algorithm step by step with a piece of paper and a pencil and write down the parts for each step.
If your goal is only to calculate a number to N precision, then you would probably be better using an already made solution, change your problem so you don't need N precision or take a look at some of the other comments/answers.