Most efficient way to get first digit of a double/float - multilingual

For example if I have a float/double variable:
float f = 1212512.028423;
double d = 938062.3453;
int f1 = 1;
int d1 = 9;
What's the fastest way to get the first digit of those number?
int first_digit(double n) {
while(n>10) n/=10;
return n;
}
Is this the most efficient?
I need an implementation that doesn't involves char/string, that would be also works (or give the best performance in their specific language). The language are Ruby, Python, C#, Java, C++, Go, JavaScript, PHP.

//Try this.
double d = 938062.3453;
int f1 = Int32.Parse(d.ToString().Substring(0, 1));

Both mentioned solutions will crash at number -0.0123. I have constructed a different method for slightly different purpose:
public static double InteligentRound(double X, int kam=0)
{ int zn = (X < 0) ? (-1) : (1); //signum of the input
X *= zn; //we work with positive values only
double exp = Math.Log10(X); //exponent of 10
exp = Math.Floor(exp);
double B = Math.Pow(10, exp);//the pure power of 10
double FD = X / B; //lies between 1 and 10
if (kam == 0) FD = Math.Round(FD);
if (kam < 0) FD = Math.Floor(FD); //Now, FD is the first digit
if (kam > 0) FD = Math.Ceiling(FD);
return (zn * FD * B);
}

Related

Program for finding nth root of the number without any external library or header like math.h

Is there any way to find nth root of the number without any external library in C? I'm working on a bare metal code so there is no OS. Also, no complete C is there.
You can write a program like this for nth root. This program is for square root.
int floorSqrt(int x)
{
// Base cases
if (x == 0 || x == 1)
return x;
// Staring from 1, try all numbers until
// i*i is greater than or equal to x.
int i = 1, result = 1;
while (result < x)
{
if (result == x)
return result;
i++;
result = i*i;
}
return i-1;
}
You can use the same approach for nth root.
Here there is a C implementation of the the nth root algorithm you can find in wikipedia. It needs an exponentiation algorithm, so I also include an implementation of a basic method for exponentiation by squaring that you can find also find in wikipedia.
double npower(double const base, int const n)
{
if (n < 0) return npower(1/base, -n)
else if (n == 0) return 1.0;
else if (n == 1) return base;
else if (n % 2) return base*npower(base*base, n/2);
else return npower(base*base, n/2);
}
double nroot(double const base, int const n)
{
if (n == 1) return base;
else if (n <= 0 || base < 0) return NAN;
else {
double delta, x = base/n;
do {
delta = (base/npower(x,n-1)-x)/n;
x += delta;
} while (fabs(delta) >= 1e-8);
return x;
}
}
Some comments on this:
The nth root algorithm in wikipedia leaves freedom for the initial guess. In this example I set it up to be base/n, but this was just a guess.
The macro NAN is usually defined in <math.h>, so you would need to define it to be suitable for your needs.
Both functions are implemented in a very rough and simple way, and their performance can be greatly improved with careful thought.
The tolerance in this example is set to 1e-8 and should be changed to something different. It should probably be proportional to the value of the base.
You can try the nth_root C function :
// return a number that, when multiplied by itself nth times, makes N.
unsigned nth_root(const unsigned n, const unsigned nth) {
unsigned a = n, b, c, r = nth ? n + (n > 1) : n == 1 ;
for (; a < r; b = a + (nth - 1) * r, a = b / nth)
for (r = a, a = n, c = nth - 1; c && (a /= r); --c);
return r;
}
Source

Bitand function in C

I want to make a bitwise AND computation over integers, but without converting them to binary numbers. For example, I have a integer "10111" (it is integer, not binary) and another integer "01001". I want bitwise AND of these numbers without converting them to binary and then making bitwise AND. I know it is not bitwise what I ask, but I want something similar to this. I know it can be interpreted initially as binary, converted to decimal and then do bitwise AND, but I do not want that. I want something like this:
int a;
int b;
int temp;
double result;
temp = a & b;
while (result != 0) {
if (result % 10 == 1)
count++;
result /= 10;
}
int length = floor(log10(abs(a))) + 1;
result = count / length;
return result;
I want this to check similarity of the Bag of Words(from natural language processing, string of 0s and 1s). I am importing Bag of Words in Monetdb, Column type should be Integer (Not string). If I have for example "10111" and "01001" in the Integer type cells, I want to get "00001" and fraction 1/5, because only 1 positions matches.
Thanks in advance
Might be a bit bulky, but it kind of works) You can optimize it yourself. I hope that I get you correctly.
IDEOne demo
#include <stdio.h>
unsigned int weirdAnd(unsigned int a, unsigned int b) {
unsigned int result = 0;
unsigned int coef = 1;
while (a && b) {
result += ((a % 10) && (b % 10)) * coef;
coef *= 10;
a /= 10;
b /= 10;
}
return result;
}
unsigned int weirdOr(unsigned int a, unsigned int b) {
unsigned int result = 0;
unsigned int coef = 1;
while (a || b) {
result += ((a % 10) || (b % 10)) * coef;
coef *= 10;
a /= 10;
b /= 10;
}
return result;
}
int main(void) {
// your code goes here
unsigned int a = 10110;
unsigned int b = 10011;
printf("%u and \n%u = \n%u\n\n", a, b, weirdAnd(a, b));
printf("%u or \n%u = \n%u\n\n", a, b, weirdOr(a, b));
return 0;
}
Output:
10110 and 10011 = 10010
10110 or 10011 = 10111
The problem is that and works on bits only, and it does not care if the input numbers are given in decimals, octal, hexadecimal, or any other way. To force and to work correctly, you must give it an input in 'binary', that is, only ones and zeroes. To do so you need to grab each digit of the input numbers as if they are binary digits.
The following works as expected:
#include <stdio.h>
int cheap_pow (int base, int exponent)
{
int result = base;
while (exponent-- > 0)
result *= base;
return result;
}
int main (void)
{
int a = 10111, b = 1001 ;
int result, factor;
printf ("BAD: %05d AND %05d = %05d\n", a, b, a & b);
printf ("GOOD: %05d AND %05d = ");
result = 0;
factor = 1;
while (a | b)
{
result += factor * ((a & 1) and (b & 1));
factor *= 10;
a /= 10;
b /= 10;
}
printf ("%05d\n", result);
}
but you must be careful when defining your inputs. When written directly into your source code, a value b = 01001 will be interpreted by the C compiler as octal (base 8), rather than decimal; and it will have the (decimal) value 513. It's just a Rule of C.
If your input comes from elsewhere, you don't need to take this into account – except when you use a standard function such as strtol, where you should carefully read the documentation because it does the same thing:
If base is zero or 16, the string may then include a "0x"
prefix, and the number will be read in base 16; otherwise, a zero
base is taken as 10 (decimal) unless the next character is '0', in
which case it is taken as 8 (octal).
An additional note is this program only will work in the range for signed int, that is (currently) up to 10 "binary" digits. If you need some more, you could switch to a larger type; but beyond that, you are better off with a not-numerical solution and use a character strings throughout.
int a, b;
int tmp = a & b;
int res = 0;
while ((tmp != 0 &&) (tmp / 10 != 0)){
int dig = tmp % 10;
res = (dig == 1)? ++res: res;
tmp /= 10;
}
Try this.

Optimizing a program for solving ax+by=c with positve integers

I am writing a program that for any given positive integers a < b < c will output YES if there is a solution to ax+by=c where x and y are also positive integers (x,y > 0), or NO if there isn't a solution. Keep in mind that I need to work with big numbers.
The approach I take for solving this problem is that I subtract b from c and I check if this number is divisable by a.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main(){
unsigned long long int a, b, c;
scanf("%I64u %I64u %I64u", &a, &b, &c);
while(c>=a+b){ //if c becomes less than a+b, than there's no sollution
c-=b;
if(c%a==0){
printf("YES");
return 0;
}
}
printf("NO");
return 0;
}
is there a more optimised way to find wether ax+by=c has positive sollutions? I tried reading about linear Diophantine equations, but all I found is a way to find integer sollutions (but not positive).
My approach so far.
Use Euclidean Algorithm to find GCD(a, b)
There are solutions (in integers) to ax + by = c if and only if GCD(a, b) divides c. No integer solutions means no positive solutions.
use Extended Euclidean Algorithm to solve the Diophantine equation and return NO if it gives non-positive solutions.
For comparisons it's hard to find examples that take longer than a second but in deciding on thousands of random equations the performance difference is noticeable. This Lecture has a solution for finding the number of positive
solutions to a Linear Diophantine Equation.
typedef unsigned long long int BigInt;
int pos_solvable(BigInt a, BigInt b, BigInt c) {
/* returns 1 if there exists x, y > 0 s.t. ax + by = c
* where 0 < a < b < c
* returns 0, otherwise
*/
BigInt gcd = a, bb = b, temp;
while (bb) { /* Euclidean Algorithm */
temp = bb;
bb = gcd % bb;
gcd = temp;
}
if (c % gcd) { /* no integer (or positive) solution */
return 0;
} else {
/* Extended Euclidean Algorithm */
BigInt s = 0, old_s = 1;
BigInt t = 1, old_t = 0;
BigInt r = b / gcd, old_r = a / gcd;
while (r > 0) {
BigInt quotient = old_r / r;
BigInt ds = quotient * s;
BigInt dt = quotient * t;
if (ds > old_s || dt > old_t)
return 0; /* will give non-positive solution */
temp = s;
s = old_s - ds;
old_s = temp;
temp = t;
t = old_t - dt;
old_t = temp;
temp = r;
r = old_r - quotient * r;
old_r = temp;
}
return 1;
}
}
The following is a comment but too big for the comment section.
This is posted to help others dig into this problem a little deeper.
OP: Incorporate any of in your post if you like.
What is still needed are some challenging a,b,c.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#define LLF "%I64u"
#define LLF "%llu"
int main(void) {
unsigned long long int a, b, c, x, y, sum, c0;
// scanf(LLF LLF LLF, &a, &b, &c);
c = c0 = ULLONG_MAX;
b = 10000223;
a = 10000169;
y = 0;
sum = a + b;
time_t t0 = time(NULL);
while (c >= sum) { //if c becomes less than a+b, than there's no solution
c -= b;
if (c % a == 0) {
break;
}
}
if (c % a == 0) {
y = (c0 - c) / b;
x = c / a;
printf("YES " LLF "*" LLF " + " LLF "*" LLF " = " LLF "\n", a, x, b, y, c);
} else {
printf("NO\n");
}
time_t t1 = time(NULL);
printf("time :" LLF "\n", (unsigned long long) (t1 - t0));
return 0;
}
Output
YES 10000169*1844638544065 + 10000223*4688810 = 18446697184563946985
time :0

algorithm to convert decimal to fraction expression

supposing I have a decimal like
0.30000000000000027
What would be the best algorithm to know the same number expressed as a fraction
So given certain x find y that satisfies x=1/y in c or haskell
I was thinking
1/3> 0.30 >1/4
Iterating left and right side til one of them converges and > becomes =
so first iteration would look like
1/1 > 0.30000000000000027 > 1/somethinghere
1/2 > 0.30000000000000027 > 1/increase or decrease this
1/3 > 0.30000000000000027 ...
I want to clarify that I could easily do
0.30000000000000027 = 30000000000000027/ 10^17
but I want to do
0.30000000000000027 = 1/x
In c or haskell
Voila (converts almost properly to a normal fraction):
int gcd(int a, int b)
{
if (a == 0) return b;
if (b == 0) return a;
if (a > b)
return gcd(b, a % b);
else
return gcd(a, b % a);
}
struct frac {
int num;
int denom;
};
struct frac to_frac(double x, int precision)
{
int denom = 1;
for (int i = 0; i < precision; i++) {
denom *= 10;
}
int num = x * denom + 0.5; // hack: round if imprecise
int gcdiv = gcd(num, denom);
struct frac f;
f.num = num / gcdiv;
f.denom = denom / gcdiv;
return f;
}
Have you looked into continued fractions? They give very good approximations of numbers.
Don't know haskell, here it is in pseudo-code:
raw_denom = 1/x;
print "1/" floor(raw_denom) " >= " x " >= 1/" ceil(raw_denom)

Subtraction without minus sign in C

How can I subtract two integers in C without the - operator?
int a = 34;
int b = 50;
You can convert b to negative value using negation and adding 1:
int c = a + (~b + 1);
printf("%d\n", c);
-16
This is two's complement sign negation. Processor is doing it when you use '-' operator when you want to negate value or subtrackt it.
Converting float is simpler. Just negate first bit (shoosh gave you example how to do this).
EDIT:
Ok, guys. I give up. Here is my compiler independent version:
#include <stdio.h>
unsigned int adder(unsigned int a, unsigned int b) {
unsigned int loop = 1;
unsigned int sum = 0;
unsigned int ai, bi, ci;
while (loop) {
ai = a & loop;
bi = b & loop;
ci = sum & loop;
sum = sum ^ ai ^ bi; // add i-th bit of a and b, and add carry bit stored in sum i-th bit
loop = loop << 1;
if ((ai&bi)|(ci&ai)|(ci&bi)) sum = sum^loop; // add carry bit
}
return sum;
}
unsigned int sub(unsigned int a, unsigned int b) {
return adder(a, adder(~b, 1)); // add negation + 1 (two's complement here)
}
int main() {
unsigned int a = 35;
unsigned int b = 40;
printf("%u - %u = %d\n", a, b, sub(a, b)); // printf function isn't compiler independent here
return 0;
}
I'm using unsigned int so that any compiler will treat it the same.
If you want to subtract negative values, then do it that way:
unsgined int negative15 = adder(~15, 1);
Now we are completly independent of signed values conventions. In my approach result all ints will be stored as two's complement - so you have to be careful with bigger ints (they have to start with 0 bit).
Pontus is right, 2's complement is not mandated by the C standard (even if it is the de facto hardware standard). +1 for Phil's creative answers; here's another approach to getting -1 without using the standard library or the -- operator.
C mandates three possible representations, so you can sniff which is in operation and get a different -1 for each:
negation= ~1;
if (negation+1==0) /* one's complement arithmetic */
minusone= ~1;
else if (negation+2==0) /* two's complement arithmetic */
minusone= ~0;
else /* sign-and-magnitude arithmetic */
minusone= ~0x7FFFFFFE;
r= a+b*minusone;
The value 0x7FFFFFFFE would depend on the width (number of ‘value bits’) of the type of integer you were interested in; if unspecified, you have more work to find that out!
+ No bit setting
+ Language independent
+ Can be adjusted for different number types (int, float, etc)
- Almost certainly not your C homework answer (which is likely to be about bits)
Expand a-b:
a-b = a + (-b)
= a + (-1).b
Manufacture -1:
float: pi = asin(1.0);
(with minusone_flt = sin(3.0/2.0*pi);
math.h) or = cos(pi)
or = log10(0.1)
complex: minusone_cpx = (0,1)**2; // i squared
integer: minusone_int = 0; minusone_int--; // or convert one of the floats above
+ No bit setting
+ Language independent
+ Independent of number type (int, float, etc)
- Requires a>b (ie positive result)
- Almost certainly not your C homework answer (which is likely to be about bits)
a - b = c
restricting ourselves to the number space 0 <= c < (a+b):
(a - b) mod(a+b) = c mod(a+b)
a mod(a+b) - b mod(a+b) = c mod(a+b)
simplifying the second term:
(-b).mod(a+b) = (a+b-b).mod(a+b)
= a.mod(a+b)
substituting:
a.mod(a+b) + a.mod(a+b) = c.mod(a+b)
2a.mod(a+b) = c.mod(a+b)
if b>a, then b-a>0, so:
c.mod(a+b) = c
c = 2a.mod(a+b)
So, if a is always greater than b, then this would work.
Given that encoding integers to support two's complement is not mandated in C, iterate until done. If they want you to jump through flaming hoops, no need to be efficient about it!
int subtract(int a, int b)
{
if ( b < 0 )
return a+abs(b);
while (b-- > 0)
--a;
return a;
}
Silly question... probably silly interview!
For subtracting in C two integers you only need:
int subtract(int a, int b)
{
return a + (~b) + 1;
}
I don't believe that there is a simple an elegant solution for float or double numbers like for integers. So you can transform your float numbers in arrays and apply an algorithm similar with one simulated here
If you want to do it for floats, start from a positive number and change its sign bit like so:
float f = 3;
*(int*)&f |= 0x80000000;
// now f is -3.
float m = 4 + f;
// m = 1
You can also do this for doubles using the appropriate 64 bit integer. in visual studio this is __int64 for instance.
I suppose this
b - a = ~( a + ~b)
Assembly (accumulator) style:
int result = a;
result -= b;
As the question asked for integers not ints, you could implement a small interpreter than uses Church numerals.
Create a lookup table for every possible case of int-int!
Not tested. Without using 2's complement:
#include <stdlib.h>
#include <stdio.h>
int sillyNegate(int x) {
if (x <= 0)
return abs(x);
else {
// setlocale(LC_ALL, "C"); // if necessary.
char buffer[256];
snprintf(buffer, 255, "%c%d", 0x2d, x);
sscanf(buffer, "%d", &x);
return x;
}
}
Assuming the length of an int is much less than 255, and the snprintf/sscanf round-trip won't produce any unspecified behavior (right? right?).
The subtraction can be computed using a - b == a + (-b).
Alternative:
#include <math.h>
int moreSillyNegate(int x) {
return x * ilogb(0.5); // ilogb(0.5) == -1;
}
This would work using integer overflow:
#include<limits.h>
int subtractWithoutMinusSign(int a, int b){
return a + (b * (INT_MAX + INT_MAX + 1));
}
This also works for floats (assuming you make a float version…)
For the maximum range of any data type , one's complement provide the negative value decreased by 1 to any corresponding value. ex:
~1 --------> -2
~2---------> -3
and so on... I will show you this observation using little code snippet
#include<stdio.h>
int main()
{
int a , b;
a=10;
b=~a; // b-----> -11
printf("%d\n",a+~b+1);// equivalent to a-b
return 0;
}
Output: 0
Note : This is valid only for the range of data type. means for int data type this rule will be applicable only for the value of range[-2,147,483,648 to 2,147,483,647].
Thankyou .....May this help you
Iff:
The Minuend is greater or equal to 0, or
The Subtrahend is greater or equal to 0, or
The Subtrahend and the Minuend are less than 0
multiply the Minuend by -1 and add the result to the Subtrahend:
SUB + (MIN * -1)
Else multiply the Minuend by 1 and add the result to the Subtrahend.
SUB + (MIN * 1)
Example (Try it online):
#include <stdio.h>
int subtract (int a, int b)
{
if ( a >= 0 || b >= 0 || ( a < 0 && b < 0 ) )
{
return a + (b * -1);
}
return a + (b * 1);
}
int main (void)
{
int x = -1;
int y = -5;
printf("%d - %d = %d", x, y, subtract(x, y) );
}
Output:
-1 - -5 = 4
int num1, num2, count = 0;
Console.WriteLine("Enter two numebrs");
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
if (num1 < num2)
{
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
for (; num2 < num1; num2++)
{
count++;
}
Console.WriteLine("The diferrence is " + count);
void main()
{
int a=5;
int b=7;
while(b--)a--;
printf("sud=%d",a);
}

Resources