Is there a more efficient way to reverse decimal numbers? - c

I am trying to reverse decimal numbers more efficient.
#include <stdio.h>
int main()
{
while(1)
{
int a,result;
scanf("%d",&a);
result=(a%10*10)+(a/10);
printf("%d\n",result);
}
}
Of course this will only work with 2 decimal numbers.
But I am trying to find out how I can reverse more numbers in an efficient way ( less code)

Sorry I need to be more specific. LESS CODE –
Ugly, but short code to "reverse" a number.
int main(){int c=getchar();if(isdigit(c))main();putchar(c);}

#include <stdio.h>
int main()
{
long in = 3456789;
long out = 0;
while(in)
{
out *= 10;
out += in % 10;
in /= 10;
}
printf("%ld\n",out);
return 0;
}
This way it will work for every type of number, no matter the number of digits, as long as it matches the data type.

Related

Weird compilation issues

#include <stdlib.h>
#include <math.h>
#include <stdio.h>
int rev (int N);
int rev(int N){
return ((N <= 9)) ? N : rev(N / 10) + ((N % 10) * (pow(10, (floor(log10(abs(N))))))) ;
}
int main(void){
int r, n;
scanf("%d", &n);
r = rev(n);
printf("%d %d", r, n);
return EXIT_SUCCESS;
}
A simple code just to find out the reverse of a number. Everything is fine. Until I put a number with more than 2 digits. Things behave weirdly, somehow the last digit is always 0 of the reversed number. I have checked out in online compilers where things behave just fine. However the problem arises when I run the code on my own machine. I am on Windows 10 with MINGw. Could you guys suggest me a solution. I previously had problems where the value stored in an int matrix changes to huge values which is practically impossible to store in int due to it's size.
Using the pow and floor function, working with floats will not always round the way you'd expect.
As already commented, work with integers.
Propose doing this digit-by-digit, and sticking with integers. A proposal for your rev() function:
int rev(unsigned int N)
{
unsigned int res = 0;
while(N>0)
{
// pick off lowest digit
unsigned int digit = N%10;
// put into result, moving up all previous digits by doing *10
res = 10*res+digit;
// remove this digit from input value
N/=10;
}
return res;
}

Factorial function only counts to 12

This factorial function starts giving wrong results with 13 and above. I have no idea why.
#include <stdio.h>
int fatorial (int p);
int main() {
int x = 13;
int test = fatorial(x);
printf("%d", test);
}
int fatorial (int p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
for x = 0, 1, 2 ...12 it prints the right result, but for 13! it prints 1932053504 which is not correct.
For x=20 it prints -210213273 for example.
I know that this is not the best way to do a factorial. Its my homework tho, it HAS to be this way.
If you try this you will get the maximum value that int can hold:
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%d\n", INT_MAX);
}
Your code causes overflow.
You could get a few more numbers if you use a bigger type, but not by very much. You could use this:
unsigned long long fatorial (unsigned long long p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
It won't get you far though. If you want bigger than that you need to find a library for bigger integers or create some custom solution. One such library is https://gmplib.org/ but that is likely out of scope for your homework.
And btw, a condition like p <= 0 is not good. It indicates that the factorial of a negative number is always one, which is false.
It is because after 12, the result of factorial of any number exceeds the size of int.
you can try the following code:
#include<stdio.h>
int main()
{
int a[100],n,counter,temp,i;
a[0]=1;
counter=0;
printf("Enter the number: ");
scanf("%d",&n);
for(; n>=2; n--)
{
temp=0;
for(i=0; i<=counter; i++)
{
temp=(a[i]*n)+temp;
a[i]=temp%10;
temp=temp/10;
}
while(temp>0)
{
a[++counter]=temp%10;
temp=temp/10;
}
}
for(i=counter; i>=0; i--)
printf("%d",a[i]);
return 0;
}
The result of the function is too big. I think big int would work better for your purposes. Big int allows you to have bigger numbers. Also, this is what I would do.
int x = the number you want to factorialize
int ans = 1;
(Then instead of all of those functions)
for(var i = x; i > 0; i--) {
ans = ans*i;
}
System.out.println(ans);
Javascript link: https://jsfiddle.net/8gxyj913/
I need to get to 100!
100! is about 9.332622e+157. Simply using standard integer types is insufficient. 32-bit int is good to 12!. With 64-bit integer math, code could get to about 21!
Could use floating point math and give up precision.
Instead consider a string approach.

Long Long Decimal Binary Representation using C

I've been trying to print out the Binary representation of a long long integer using C Programming
My code is
#include<stdio.h>
#include <stdlib.h>
#include<limits.h>
int main()
{
long long number, binaryRepresentation = 0, baseOfOne = 1, remainder;
scanf("%lld", &number);
while(number > 0) {
remainder = number % 2;
binaryRepresentation = binaryRepresentation + remainder * baseOfOne;
baseOfOne *= 10;
number = number / 2;
}
printf("%lld\n", binaryRepresentation);
}
The above code works fine when I provide an input of 5 and fails when the number is 9223372036854775807 (0x7FFFFFFFFFFFFFFF).
1.Test Case
5
101
2.Test Case
9223372036854775807
-1024819115206086201
Using a denary number to represent binary digits never ends particularly well: you'll be vulnerable to overflow for a surprisingly small input, and all subsequent arithmetic operations will be meaningless.
Another approach is to print the numbers out as you go, but using a recursive technique so you print the numbers in the reverse order to which they are processed:
#include <stdio.h>
unsigned long long output(unsigned long long n)
{
unsigned long long m = n ? output(n / 2) : 0;
printf("%d", (int)(n % 2));
return m;
}
int main()
{
unsigned long long number = 9223372036854775807;
output(number);
printf("\n");
}
Output:
0111111111111111111111111111111111111111111111111111111111111111
I've also changed the type to unsigned long long which has a better defined bit pattern, and % does strange things for negative numbers anyway.
Really though, all I'm doing here is abusing the stack as a way of storing what is really an array of zeros and ones.
As Bathsheba's answer states, you need more space than is
available if you use a decimal number to represent a bit sequence like that.
Since you intend to print the result, it's best to do that one bit at a time. We can do this by creating a mask with only the highest bit set. The magic to create this for any type is to complement a zero of that type to get an "all ones" number; we then subtract half of that (i.e. 1111.... - 0111....) to get only a single bit. We can then shift it rightwards along the number to determine the state of each bit in turn.
Here's a re-worked version using that logic, with the following other changes:
I use a separate function, returning (like printf) the number of characters printed.
I accept an unsigned value, as we were ignoring negative values anyway.
I process arguments from the command line - I tend to find that more convenient that having to type stuff on stdin.
#include <stdio.h>
#include <stdlib.h>
int print_binary(unsigned long long n)
{
int printed = 0;
/* ~ZERO - ~ZERO/2 is the value 1000... of ZERO's type */
for (unsigned long long mask = ~0ull - ~0ull/2; mask; mask /= 2) {
if (putc(n & mask ? '1' : '0', stdout) < 0)
return EOF;
else
++printed;
}
return printed;
}
int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i) {
print_binary(strtoull(argv[i], 0, 10));
puts("");
}
}
Exercises for the reader:
Avoid printing leading zeros (hint: either keep a boolean flag that indicates you've seen the first 1, or have a separate loop to shift the mask before printing). Don't forget to check that print_binary(0) still produces output!
Check for errors when using strtoull to convert the input values from decimal strings.
Adapt the function to write to a character array instead of stdout.
Just to spell out some of the comments, the simplest thing to do is use a char array to hold the binary digits. Also, when dealing with bits, the bit-wise operators are a little more clear. Otherwise, I've kept your basic code structure.
int main()
{
char bits[64];
int i = 0;
unsigned long long number; // note the "unsigned" type here which makes more sense
scanf("%lld", &number);
while (number > 0) {
bits[i++] = number & 1; // get the current bit
number >>= 1; // shift number right by 1 bit (divide by 2)
}
if ( i == 0 ) // The original number was 0!
printf("0");
for ( ; i > 0; i-- )
printf("%d", bits[i]); // or... putchar('0' + bits[i])
printf("\n");
}
I am not sure what you really want to achieve, but here is some code that prints the binary representation of a number (change the typedef to the integral type you want):
typedef int shift_t;
#define NBITS (sizeof(shift_t)*8)
void printnum(shift_t num, int nbits)
{
int k= (num&(1LL<<nbits))?1:0;
printf("%d",k);
if (nbits) printnum(num,nbits-1);
}
void test(void)
{
shift_t l;
l= -1;
printnum(l,NBITS-1);
printf("\n");
l= (1<<(NBITS-2));
printnum(l,NBITS-1);
printf("\n");
l= 5;
printnum(l,NBITS-1);
printf("\n");
}
If you don't mind to print the digits separately, you could use the following approach:
#include<stdio.h>
#include <stdlib.h>
#include<limits.h>
void bindigit(long long num);
int main()
{
long long number, binaryRepresentation = 0, baseOfOne = 1, remainder;
scanf("%lld", &number);
bindigit(number);
printf("\n");
}
void bindigit(long long num) {
int remainder;
if (num < 2LL) {
printf("%d",(int)num);
} else {
remainder = num % 2;
bindigit(num/2);
printf("%d",remainder);
}
}
Finally I tried a code myself with idea from your codes which worked,
#include<stdio.h>
#include<stdlib.h>
int main() {
unsigned long long number;
int binaryRepresentation[70], remainder, counter, count = 0;
scanf("%llu", &number);
while(number > 0) {
remainder = number % 2;
binaryRepresentation[count++] = remainder;
number = number / 2;
}
for(counter = count-1; counter >= 0; counter--) {
printf("%d", binaryRepresentation[counter]);
}
}

rip off a number out of a fraction

I am working on a project and I have an idea on how to start. Basically this is how the program runs:
$ ./rulerbuddy 2.25
2.25 is exactly 2 1/4
So, I kind of have the idea that I need first to rip off the whole number which in this case is '2' then start manipulating the fraction to get the result. My question is how can I rip off that whole number from the decimal fraction? Any ideas, steps, guide is appreciated. Thank you.
Take out the whole number and consider only the decimal part (do a sscanf(input, "%d.%d", &intPart, &fracPart) to take them apart).
Count the digits after the decimal point; your starting fraction is digits/10^number of digits, i.e. in your case 25/100;
Now you can simplify it finding the greatest common divisor (e.g. with Euclid algorithm) and dividing both terms by it.
Quick example of how this can be implemented:
#include <stdio.h>
#include <math.h>
struct Fraction
{
int n;
unsigned int d;
};
int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a-b*(a/b));
}
void simplify(struct Fraction * f)
{
int divisor=gcd(f->n, f->d);
f->n/=divisor;
f->d/=divisor;
}
int main(int argc, char * argv[])
{
int intPart;
unsigned int fracPart;
struct Fraction f;
if(argc<2)
{
puts("Not enough arguments.");
return 1;
}
if(sscanf(argv[1], "%d.%u", &intPart, &fracPart)!=2)
{
puts("Invalid input.");
return 2;
}
f.n=fracPart;
f.d=fracPart!=0?(int)pow(10., floor(log10(fracPart)+1)):1;
simplify(&f);
printf("%s is exactly: %d %d/%u\n", argv[1], intPart, f.n, f.d);
return 0;
}
if(num < 0)
num = num * (-1);
then
Just type cast the number explicitly to `int`
Use the standard library function floor
#include <math.h>
int WholeNumber(double number)
{
return (int)floor(number);
}
int main(void)
{
int N;
N = WholeNumber(2.25);
printf("The Whole part is %d\n", N); // this will print 2
}
Try a regex
http://rubular.com/r/KkE34B4ODQ
I've set that up to work for your example, you may need to alter it based on what your program provides for whole numbers (ie.e 2 0/1) or whatever.
The first group is the whole
second is numerator
third is denominator

How to create a datatype to hold 200+ digit long numbers in C?

OK,so I am trying to solve this problem: http://www.spoj.pl/problems/FCTRL2/
And using what I know about c, I have come up with this code:
#include <stdio.h>
#include <conio.h>
long double factorial(int);
int main()
{
long double num[100], fact[100];
int i = 0, ex;
scanf("%d", &ex);
for ( i = 0; i < ex; i++ )
{
scanf("%lf", &num[i]);
}
i = 0;
printf("\n");
for (i = 0; i < ex; i++ )
{
fact[i] = factorial(num[i]);
printf("%.0lf\n", fact[i]);
}
getch();
return 0;
}
long double factorial(int num)
{
long double onum, fact;
int i;
fact = 1;
onum = num;
for ( i = 1; i < onum; i++ )
{
fact = fact * num;
num--;
}
return fact;
}
The problem is that long double is not long enough to hold values as long as 100! So, how can I create a datatype that can hold this large value?
For this particular problem, GMP is indeed an overkill.
In fact, even the struct presented by Carl Norum, while useful and more general, contains more than what you will need. In particular, since all factorials are positive integers you don't need to worry about the sign.
Also, it's not necessary to implement addition, subtraction, or even general multiplication. You only need to worry about multiplying one of these "bignums" by an integer, which isn't too hard.
Here's a stub for the multiplication operation
void multiply( mybignum bn, int factor ) {
// for each of the digits in 'bn'
// multiplies 'factor' by the particular digit
// adds the previous remainder and stores
// the new carry value
}
There is no native data type that can hold numbers that large. Check out the GNU Multiple Precision Arithmetic Library.
GMP might be a little overkill for your particular problem, but it will get the job done. You could also write your own little arbitrary precision library to do it.
Edit - an example bignum type:
struct mybignum
{
int length;
int sign;
int digit[200];
};
You can just implement the grade-school algorithms for addition, subtraction, multiplication, etc. using that structure, and presto - 200-digit number support.

Resources