Language – Java | Type – Program | Last date 8-Jul-2009 9:00 p.m. IST | Points 5

Write a program to divide two floating point numbers - No using the '/' sign in the entire program – That's all folks.

I think I had a similar Puzzle before - maybe it might help - Puzzle 10 & its solution here - Puzzle 10 Solution

Got an answer? Leave it here.

Short of implementing a floating point number division algorithm, two solutions come to mind:

ReplyDelete1. use math: a / b = a * b**-1

a * Math.pow(b, -1)

2. use a different notation for /

a \u002f b

public static void main(String[] args) {

ReplyDeleteSystem.out.println(divide1(5, 2));

System.out.println(divide2(5, 2));

System.out.println(divide3(5, 2));

}

public static double divide1(double x, double y) {

return x * Math.pow(y, -1);

}

public static double divide2(double x, double y) {

return BigDecimal.valueOf(x).divide(BigDecimal.valueOf(y)).doubleValue();

}

public static double divide3(double x, double y) {

return x \u002F y;

}

A mathematical solution would be the use of logarithms.

ReplyDeletedouble d1 = 42d;

double d2 = 23d;

double q = Math.exp(Math.log(d1) - Math.log(d2));

System.out.println("q = " + q);

Or the use of pow to invert d2:

double q2 = d1 * Math.pow(d2, -1);

System.out.println("q2 = " + q2);

And a sneaky one where one can argue whether I actually used the '/' or not:

double q3 = d1 'backslash'u002f d2;

(Replace 'backslash' with the backslash here (the comment field did not accept my comment with the backslash in place.)

This trick could be used to create lots of new weird twisters....

Random r = new Random();

ReplyDeletedouble a = r.nextDouble(), b = r.nextDouble();

double result = a * Math.pow(b, -1);

public static void main(String[] args) {

ReplyDeletefloat a = 1.0f;

float b = 3.0f;

System.out.println("Correct: " + a / b);

System.out.println("Test: " + a * (float) Math.pow(b, -1f));

}

Ooops, there is no actual need for power to be float. So Math.pow(b, -1) will work fine too.

ReplyDelete{

ReplyDeletefloat a = 1; float b = 2;

float sum = a * Math.pow(b, -1f);

}

public float divide (float numerator, float denominator){

ReplyDeletereturn (float) (numerator * Math.pow(denominator, -1));

}

Based on the principle that division is simply multiplication using the inverse of the divisor, which can be computed as divisor^(-1) power (I don't think the entire program is really all that necessary, here the desired result is for a / b):

ReplyDelete//using float as the type

public static float divide(float a, float b) {

return (float) (a * Math.pow(b, -1));

}

//or for double as the floating point type

public static double divide(double a, double b) {

return a * Math.pow(b, -1);

}