Number Reversal in c++ - c++

When I pass an odd digit number > 1 to the function, I am getting 1 less than the actual result I should be getting and the code is working perfectly fine for an even digit number, I am not able to figure out why.
int rev_number(int num){
int arr [10];
int i=0;
int j=0;
int rev_num=0;
while(num > 0){
arr[i] = num%10;
num = num/10;
i++;
}
i--;
while(i>=0){
rev_num += arr[j] * pow(10,i);
j++;
i--;
}
return rev_num;
}

You should avoid using pow which return a double while you only want to manipulate integers. For example, imagine if the result of arr[j] * pow(10,i) is 753.99..., the cast would only put 753 in rev_num! In some cases, that will work, but not always. It's a fifty-fifty chance to work.
Try replacing:
rev_num += arr[j] * pow(10,i);
to
rev_num = rev_num * 10 + arr[j];
Have you tried to round or to add .5? Does that also fix your problem?

How about the following simple code
int reverseNumber(int num) {
int reverse = 0;
while(num > 0) {
reverse = reverse*10 + num%10;
num = num/10;
}
return reverse;
}

Since pow deals with floating point values, it's integer representation may get truncated, so certain values may end up being lower than expected.
A better solution is to use integer math, such as this:
while(i>=0){
rev_num *= 10;
rev_num += arr[j];
j++;
i--;
}
There are several other ways to express the same thing, and storing the values in an array isn't strictly necessary, you could just multiply the modulo value back in.
However, my favourite "reverse a number" is to read it in as a string, and then use the standard reverse function.
So, something like this:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << s << std::endl;
}

All code examples of the function showed here are invalid because the function does not process valid integer 0. So I decided to show a correct function realization.:)
using System;
namespace ReverseNumberExercise
{
class Program
{
static int ReverseNumber(int x)
{
int y = 0;
do
{
long digit;
x = ( int )Math.DivRem( x, 10L, out digit );
y = y * 10 + ( int )digit;
} while ( x != 0 );
return (y);
}
static void Main()
{
while (true)
{
Console.Write("Enter an integral number: ");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) break;
int x;
if (!int.TryParse(input, out x))
{
Console.WriteLine("Invalid number. Try again.");
}
Console.WriteLine("Reversed number is: {0}", ReverseNumber(x));
Console.WriteLine();
}
Console.WriteLine("\nGood bye!");
}
}
}

Related

Unıque Random Number Check form Array c++

#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.

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');}

converting a string (containing numbers) into an integer and returning that integer

i'm working on a code right now in C++, in which i'm supposed to make a function which receives a string of numbers and converts it into an integer then returns that value. for example if i pass "4569" as string, it will return 4569 integer value.
can anyone help me point out where i'm wrong ??? thanks in advance :)
#include<iostream>
#include<cstdlib>
using namespace std;
void getInput(char arr[] , int size )
{
cout<<"ENTER THE ARRAY"<<endl;
cin.getline(arr,size);
}
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for( int i=y ; i>=0 ; i--)
{
int n= source[i];
sum = (sum + (n * multiply));
multiply = (multiply *10);
}
return sum;
}
int main()
{
const int size =100;
char inputArr [size];
getInput (inputArr, size );
int x = stringToInteger (inputArr );
cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
cout<<x<<endl;
return 0;
}
First, you're starting at the character after the end of the string. If the length (returned by strlen) is y, then valid indexes are 0 <= i < y. So your loop wants to start from y-1.
for( int i=y-1 ; i>=0 ; i--)
^^
Then, you need to convert each ASCII digit into a value from 0 to 9, by subtracting the ASCII value for '0':
int n= source[i] - '0';
^^^^^
Then you should probably detect and handle erroneous input, including values that are too large to be represented by int.
Then, once you've learnt how to implement this in C, throw it away and use the C++ library:
std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
Try,
#include <stdlib.h>
and in your main():
int x = atoi(inputArr);
I'm not sure why you aren't using atoi or std::stoi, but your algorithm has a logical flaw:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
That said, if this was something other than a homework assignment, you should be using the solutions posted https://stackoverflow.com/a/18238566/529761 or https://stackoverflow.com/a/18238682/529761 (depending on your language requirements).
Also, even this change has 1 potential problem: If the source contains non-numeric characters, it will not work properly. A simple way to approach it is to break out if you encounter a character that shouldn't be there:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
if (n < 0 || n > 9)
break;
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
No need to call a strlen -- until you are allowed to use library functions (the above-mentioned atoi and strtol), you can use this:
int stringToInteger(char *source)
{
int sum = 0;
if (source)
while (*source >= '0' && *source <= '9')
{
sum = 10*sum + *source - '0';
source++;
}
return sum;
}
As implied in about every other answer, you forgot there is a difference between the ASCII character '0' and the binary value 0.

reverse the position of integer digits?

i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
Here is a solution
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
If you try it once as an example, you'll see your error.
Input: 12
first loop:
out: 12%10 = 2 / 1 = 2
i = 100
test: 12/100 = 0 (as an integer)
aborts one too early.
One solution could be testing
(num % i) != num
Just as one of many solutions.
Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?
replace your while statement
with
while (i<10*num)
If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:
output = 0;
while (input !=0)
output *= 10
output += input % 10
input /= 10
}
print output
The other obvious possibility would be to convert to a string first, then print the string out in reverse:
std::stringstream buffer;
buffer << input;
cout << std::string(buffer.str().rbegin(), buffer.str().rend());
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
int Res = x % (10 );
x /= 10;
out *= 10;
out += Res;
}
cout << out;
}
This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.
The following code works for a two-digit number only.
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 0;
}
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
c=a%10;
d=(d*10)+c;
a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
cout<<"The entered number is palindom"<<endl;
}
else
{
cout<<"The entered number is not palindom"<<endl;
}
}
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e.
7 in 8 bit = 00000111 -> 11100000
7 in 4 bit = 0111 -> 1110
public class TestDS {
public static void main(String[] args) {
System.out.println(recursiveReverse(234));
System.out.println(recursiveReverse(234 ,0));
}
public static int reverse(int number){
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
return reversedNumber;
}
private static int reversenumber =0;
public static int recursiveReverse(int number){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number);
}
public static int recursiveReverse(int number , int reversenumber){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number,reversenumber);
}
}
I have done this simply but this is applicable upto 5 digit numbers but hope it helps
#include<iostream>
using namespace std;
void main()
{
int a,b,c,d,e,f,g,h,i,j;
cin>>a;
b=a%10;
c=a/10;
d=c%10;
e=a/100;
f=e%10;
g=a/1000;
h=g%10;
i=a/10000;
j=i%10;
cout<<b<<d<<f<<h<<j;
}`

Calculate the factorial of an arbitrarily large number, showing all the digits

I was recently asked, in an interview, to describe a method to calculate the factorial of any arbitrarily large number; a method in which we obtain all the digits of the answer.
I searched various places and asked in a few forums. But I would like to know if there is any way to accomplish this without using libraries like GMP.
Thank you.
GNU Multiprecision library is a good one! But since you say using of external libraries are not allowed, only way I believe its possible is by taking an array of int and then multiplying numbers as you do with pen on paper!
Here is the code I wrote some time back..
#include<iostream>
#include<cstring>
int max = 5000;
void display(int arr[]){
int ctr = 0;
for (int i=0; i<max; i++){
if (!ctr && arr[i]) ctr = 1;
if(ctr)
std::cout<<arr[i];
}
}
void factorial(int arr[], int n){
if (!n) return;
int carry = 0;
for (int i=max-1; i>=0; --i){
arr[i] = (arr[i] * n) + carry;
carry = arr[i]/10;
arr[i] %= 10;
}
factorial(arr,n-1);
}
int main(){
int *arr = new int[max];
std::memset(arr,0,max*sizeof(int));
arr[max-1] = 1;
int num;
std::cout<<"Enter the number: ";
std::cin>>num;
std::cout<<"factorial of "<<num<<"is :\n";
factorial(arr,num);
display(arr);
delete[] arr;
return 0;
}
'arr' is just an integer array, and factorial is a simple function that multiplies the given number to the 'large number'.
Hope this solves your query..
The accepted answer is fine, but this is C++; we can do better. Let's make the start of our own Bignum class, with a totally unbounded number of digits.
For the highest efficiency we would work with pure binary numbers, packing each array element with as many bits as we can efficiently handle. The simpler approach is to store a single decimal digit in each element. Here I've gone for a compromise, storing 9 decimal digits in each uint32_t element.
The data is stored little-endian, since it's much easier to extend a vector at the end when we need higher order elements.
Once we have this class, the factorial function is simplicity itself.
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <stdint.h>
#include <vector>
class Bignum
{
public:
Bignum(int value)
{
assert(value >= 0 && value <= 999999999);
parts.push_back(value);
}
Bignum& operator*=(int rhs)
{
assert(rhs >= 0 && rhs <= 999999999);
uint32_t carry = 0;
for (size_t i = 0; i < parts.size(); i++)
{
uint64_t product = (uint64_t)parts[i] * (uint64_t)rhs + carry;
parts[i] = (uint32_t)(product % 1000000000LL);
carry = (uint32_t)(product / 1000000000LL);
}
if (carry != 0)
parts.push_back(carry);
return *this;
}
friend std::ostream & operator<<(std::ostream& stream, const Bignum& num);
private:
std::vector<uint32_t> parts;
};
inline std::ostream& operator<<(std::ostream& stream, const Bignum& num)
{
char oldfill = stream.fill('0');
for (std::vector<uint32_t>::const_reverse_iterator it = num.parts.rbegin(); it != num.parts.rend(); it++)
stream << *it << std::setw(9);
stream.fill(oldfill);
stream.width(0);
return stream;
}
Bignum factorial(int n)
{
Bignum fac = 1;
for (int i = 2; i <= n; i++)
fac *= i;
return fac;
}
int main(int argc, char* argv[])
{
for (int n = 0; n <= 52; n++)
std::cout << factorial(n) << std::endl;
return 0;
}
Nice solution by Srivatsan Iyer and my suggestion are :
It can still be made more memory efficient by using unsigned char array rather than using int array to store digits.
It will take only 25% of the memory need to that of int array.
For the best memory optimization , we can also use single byte to represent a 2 digits.
Since only 4 bits are suffice to represent any digit from 0 to 9.
So we can pack two digits in a single byte using bitwise operations.
It will take 12.5% of the memory need to that of int array.
A BigInteger class would solve your problem, and the C implementation above gives you an idea about how a BigInt would be implemented, except that the code is optimized for speed and tailored to computing the factorial only.
Well, you'd have to write your own math routines using arrays. That's very easy for addition, multiplication is a bit harder, but still possible.
EDIT: Wanted to post an example, but Srivatsan Iyer's example is just fine.
I have a solution for calculating the factorial, which works fine for at least n<=15000. Factorial of 10000 can be calculated under 1 sec and that for calculating the factorial takes less than 2 seconds. (Of course your question tells nothing about time constraints and these timings are totally dependent on the machine). Anyways, the concept is quite simple. I use a char array. The first character of the array is '1'. The LSBs are stored from the index starting with 0. A variable(m according to my program) keeps track of the factorial length. The final value of m is the number of digits in the factorial and the (m-1)th element of the char array is MSB of the factorial.
As the loop iterates, the characters get added in the right side of the array. A variable 'c' keeps track of the carry.
The drawbacks of using the array is left over chunks of unused bytes. And beyond a certain point, you cannot reserve space for an array.Besides, arrays tend to get slow.
You can check out my program on ideone: http://ideone.com/K410n7
I believe my solution can still be optimized. Please suggest how.
include<stdio.h>
char res[200000];
inline int fact(int n)
{
int i,j;
register int m,c;
m=1;
res[0]='1';
for(i=2;i<=n;i++)
{
c=0;
for(j=0; j< m; j++){
c =((res[j]-48)*i)+c;
res[j]=(c%10)+48;
c=c/10;
}
while(c>0){
res[m]=(c%10)+48;
c=c/10;
m++;
}
}
return m;
}
int main() {
int n,i,d;
scanf("%d",&n);
d=fact(n);
for(i=d-1;i>=0;i--)
printf("%c",res[i]);
return 0;
}
#include <iostream>
using namespace std;
int main ()
{
int i,n,p=1;
cout<<"Enter a number: ";
cin>>n;
cout<<endl;
for (i=1;i<=n; i++)
{
cout<<i<<" X ";
p=p*i;
}
cout<<endl<<endl<<p<<" factorial of "<<n;
return 0;
}
That's actually pretty easy. Here are two ways. One is exact and one is an approximation. For exact figures, any number over 10,000 is going to take multiple seconds to calculate. Approximating it will take microseconds, until you get into the millions. It is Stirling's approximation if anyone is interested.
Factorial of 10,000,000 is aprox 1.2024234127436e+65657059 This took 5.9 seconds Finding the exact amount would take 34 days.
<?php
$test= 3579;
echo 'Factorial of '.$test.'<br><br>';
$tm= microtime( true);
echo 'Exact '.( $f= factorialexact( $test)).' e+'.(strlen( $f)-1).' missing decimal place after first digit<br>';
echo ( microtime( true) - $tm). ' seconds<br><br>';
$tm= microtime( true);
echo 'Aprox '.factorialapprox( $test).'<br>';
echo ( microtime( true) - $tm). ' seconds<br><br>';
function factorialexact( $n){
$f= '1';
for ( $i=$n; $i>1; $i--){
$f= JL_bcmul( $f, (''.$i));
}
return $f;
}
function factorialapprox( $n){
// Stirling's factorial approximation
// aprox factorial n = sqrt( 2 * pi * n) * n^n / e^n
// store in t the easy part, calc the first term easily
$t= sqrt( 2 * 3.14159265358979 * $n);
// things get tough from here because for large n
// n^n can blow away floating point pachages
// declare exponent of the number
$e= 0;
// the remaining terms are n^n / e^n
// both n and e (natural log) are raised to the same power
// that is n, just negative of each other
for ( $i=0; $i<$n; $i++){
// loop to
// mulitply by n and divide by e for each iteration
$t= $t * $n / 2.71828182845904;
// exponents are going to get away from us
// so reduce or increase t
while ( $t>1000){
$t= $t/1000;
$e= $e+3;
}
while ( $t<0.001){
$t= $t*1000;
$e= $e-3;
}
}
// garentee the base number is between 1 and 10
while ( $t>=10){
$t= $t/10;
$e= $e+1;
}
while ( $t<1){
$t= $t*10;
$e= $e-1;
}
// return at a floating string.
// do not use parseFloat() or floatval()
// $v= explode( 'e', $result); $floatvalue= $v[0] * pow( 10, $v[1]);
// won't work either. $v[1] is way too large
// the exponent can easily be in the tens of thousands
$p= '-';
if ( $e>=0){ $p= '+'; }
return $t.'e'.$p.$e;
}
function JL_bcmul( $a, $b){
if ( function_exists( 'bcmul')){
return bcmul( ( ''.$a), (''.$b));
}
$s= array();
for ($i=0; $i < count( $a) + count( $b); $i++){ $s[$i]= '0'; }
$t= 0;
for ($i=0; $i < strlen( $b); $i++){
for ($j=0; $j < strlen( $a); $j++){
$t= $s[$i+$j] + intval( $a[strlen( $a) - $j - 1]) * intval( $b[ strlen( $b) - $i - 1]);
$s[$i+$j]= $t % 10;
$s[$i+$j+1]= $s[$i+$j+1] + floor( $t / 10);
}
}
$s= array_reverse( $s);
return trim( trim(( implode( '', $s).'_'), '0'), '_');
}
#include<stdio.h>
#include<string.h>
char f[10000];
char factorial[1010][10000];
void multiply(int k){
int ci,sum,i;
int len = strlen(f);
ci=0;
i=0;
while(i<len){
sum=ci+(f[i] - '0') * k;
f[i] = (sum % 10) + '0';
i++;
ci = sum/10;
}
while(ci>0){
f[i++] = (ci%10) + '0';
ci/=10;
}
f[i]='\0';
for(int j=0;j<i;j++)factorial[k][j]=f[j];
factorial[k][i]='\0';
}
void fac(){
int k;
strcpy(f,"1");
for(k=2;k<=1000;k++)multiply(k);
}
void print(int n){
int i;
int len = strlen(factorial[n]);
printf("%d!\n",n);
for(i=len-1;i>=0;i--){
printf("%c",factorial[n][i]);
}
printf("\n");
}
int main()
{
int n;
factorial[0][0]='1';
factorial[1][0]='1';
fac();
while(scanf("%d",&n)==1){
print(n);
}
return 0;
}
Code shown below :
#include<bits/stdc++.h>
using namespace std;
#define MAX 5000
void factorial(int n)
{
int carry , res_size = 1, res[MAX];
res[0] = 1;
for(int x=2; x<=n; x++)
{
carry = 0;
for(int i=0; i<res_size; i++)
{
int prod = res[i]*x + carry;
res[i] = prod % 10;
carry = prod/10;
}
while (carry)
{
res[res_size++] = carry%10;
carry = carry/10;
}
}
for(int i=res_size-1; i >= 0; i--)
{
cout<<res[i];
}
}
int main()
{
int n;
cin>>n;
factorial(n);
cout<<endl;
return 0;
}
Since everyone voted for Srivatsan, I just have a doubt related to the problem. Do you need to store all the digits? If yes, then Srivatsan's solution is fine. If not, why not just display the numbers, as you calculate the factorial? I am not formatting the output properly, but this could serve the purpose.
int factorial(int num)
{
if (num <= 0)
return 1;
else
{
std::cout << num << std::endl;
return num * factorial(num - 1);
}
}
UPDATE
For all the downvoters, though this 5 year old post, and the output for factorial(3);
3
2
1
6 // this is the result of the factorial and the digits above are the ones all the digits in the calculation.
I thought this is what asked.