Search the Community
Showing results for tags 'more maths'.
-
Here's a fun little bit of theory for you I wouldn't usually ask this sort of stuff, I'd spend days trying to figure it out myself, but I think other people are going to like this one. 123.456 in base -10 should be: 284.664 Why? Well, if you apply the rules for normal numeric bases, it is possible: 2 * (-10)^2 = 200 8 * (-10)^1 = -80 4 * (-10)^0 = 4 6 * (-10)^-1 = -0.6 6 * (-10)^-2 = 0.06 4 * (-10)^-3 = -0.004 The sum of all of those is 123.456, so it works *in theory*. Has anyone got any idea how that would look as a computer program? Obviously the traditional method is not going to work. I've been racking my brains to try and describe the method of doing it by hand as a program but it made me realise I was using trial and error a lot of the time. I suppose a related problem is log-b(a), as it should be complex, but ceiling(log) is also supposed to be the number of digits needed to display the number. For those interested, here is my version for positive bases (greater than 2). Ideally I need a simple modification to support negatives. Not going to happen though. #include <stdio.h> #include <stdlib.h> char* tobase( int, int ); unsigned int ilog2( unsigned int ); int main( int argc, char* argv[] ) { int ret; int n; int base; char* t; if ( argc != 3 ) { puts( "Usage: tobase NUMBER BASE" ); ret = 1; } else { n = atoi( argv[1] ); base = atoi( argv[2] ); t = tobase( n, base ); if ( t == NULL ) { ret = 2; puts( "Error." ); } else { puts( t ); free( t ); ret = 0; } } return ret; } char* tobase( int i, int base ) { const char symbols[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; char* ret; int lbn; int neg; int c; if ( ( base < 2 ) || ( base > 64 ) ) { ret = NULL; } else { if ( i < 0 ) { neg = 1; i = -i; } else { neg = 0; } lbn = ilog2( i ) / ilog2( base ) + 1; c = lbn + neg; ret = ( char* )malloc( ( c + 1 ) * sizeof( char ) ); ret[c--] = '\0'; if ( neg ) { ret[0] = '-'; } do { ret[c--] = symbols[i % base]; i /= base; } while ( i ); } return ret; } unsigned int ilog2( unsigned int i ) { unsigned int ret; ret = 0; if ( i > 0xFFFF ) { ret = 16; i >>= 16; } if ( i > 0xFF ) { i >>= 8; ret |= 8; } if ( i > 0xF ) { i >>= 4; ret |= 4; } if ( i > 0x3 ) { i >>= 2; ret |= 2; } ret |= ( i >> 1 ); return ret; }