Converting an If-Else statement into a Formula - java

I have code as follows:
`if (a <= 10){
z = 5;
} else {
z = -1;
}`
I figured out that when s(10 - a) = |10 - a| / (10 - a) where it outputs a 1 or -1. It outputs 1 if a < 10 and -1 if a > 10.
Then, I just solve the linear equation z = s(10 - a) * m + b, to find constants m and b.
5 = 1 * m + b and -1 = -1 * m + b
Which outputs b = 2, m = 3.
Then this can be modeled as z = 3 * s(10 - a) + 2.
Now the question becomes more tricky. What if I have two variables in nested if statements? Such as:
`if (a <= 10){
if(b <= 3){
z = 3;
} else {
z = 1;
}
} else {
if(b <= -5){
z = -11;
} else {
z = 4;
}
}`
I tried to solve this using another series of linear equations.
3 = A * s(10 - a) + B * s(3 - b) + C
1 = A * s(10 - a) + B * s(3 - b) + C
-11 = A * s(10 - a) + D * s(-5 - b) + C
4 = A * s(10 - a) + D * s(-5 - b) + C
with A, B, C, D as constants. However, this isn't giving me the right answer. What am I doing wrong?

An if statement can be transformed into a formula by using the following trick: we need to find a formula that's 1 if the if statement is true and 0 otherwise. We can use the signum function for this:
f(x, y) = (sign(y - x) + 1) / 2
f(x, y) is 1 if x < y and 0 if x > y. The inverse g(x, y) = 1 - f(x, y).
So with those two formulas we can easily put together the whole thing:
f(a, 10) * (f(b, 3) * 3 + g(b, 3) * 1) + g(a, 10) * (f(b, -5) * -11 + g(b, -5) * 4)

A general equation of the form:
((z2+z1)/2) + (|z2-z1|/2)*f(a,b)
where f(a,b) = |a-b|/(a-b)
In english:
(midpoint between 2 given z values) +
(distance from midpoint to either z value)*|a-b|/(a-b)
trying this on the original example:
if (a <= 10){
z = 5;
} else {
z = -1;
}
you get:
z1=5 z2=-1
f(a,b)=f(10,a)=|10-a|/(10-a)
plugging these in...
((5-1)/2) + (|5-(-1)|/2)*|10-a|/(10-a)
simplifying to your original z = 3 * s(10 - a) + 2
When applying this to nested conditional:
if (a <= 10) {
... // z1
} else {
... // z2
}
for z1 i get z1 = 2 + |3-b|/(3-b)
for z2 i get -3.5 + 7.5*(|-5-b|/(-5-b)). z1 seems ok but z2 doesn't seem to work since if you tried b=0 you have z2 = -3.5 - 7.5*(1) but since 0>-5 you would expect z2 = 4 since:
if (b <= -5) {
z = -11;
} else {
z = 4;
}
to get the correct expression i swapped the definition of f(a,b) = |a-b|/(a-b) to f(a,b) = |b-a|/(b-a) the new result being z2 = -3.5 + 7.5*(|b+5|/(b+5)) and testing b=0 gives the correct result of 4. This reduces the nested conditional to look like the simpler problem
if (a <= 10) z = 2 + |3-b|/(3-b)
else z = -3.5 + 7.5*(|b+5|/(b+5))
which assuming you know b you can apply the same method above used for the simple case.

Related

(a * b) / c MulDiv and dealing with overflow from intermediate multiplication

I need to do the following arithmetic:
long a,b,c;
long result = a*b/c;
While the result is guaranteed to fit in long, the multiplication is not, so it can overflow.
I tried to do it step by step (first multiply and then divide) while dealing with the overflow by splitting the intermediate result of a*b into an int array in size of max 4 ( much like the BigInteger is using its int[] mag variable).
Here I got stuck with the division. I cannot get my head around the bitwise shifts required to do a precise division. All I need is the quotient (don't need the remainder).
The hypothetical method would be:
public static long divide(int[] dividend, long divisor)
Also, I am not considering using BigInteger as this part of the code needs to be fast ( I would like to stick to using primitives and primitive arrays).
Any help would be much appreciated!
Edit:
I am not trying to implement the whole BigInteger myself. What I am trying to do is to solve a specific problem (a*b/c, where a*b can overflow) faster than using the generic BigInteger.
Edit2: It would be ideal if it could be done in a clever way, by not getting overflow at all, some tips surfaced in the comments, but I am still looking for one that is correct.
Update:
I tried to port BigInteger code to my specific needs, without object creation, and in the first iteration, I got ~46% improvement in speed comparing to using BigInteger (on my development pc).
Then I tried a bit modified #David Eisenstat solution, which gave me ~56 % (I ran 100_000_000_000 random inputs from Long.MIN_VALUE to Long.MAX_VALUE) reduced run times(more than 2x) comparing to BigInteger (that is ~18% compared to my adapted BigInteger algo).
There will be more iterations on optimization and testing, but at this point, I think I must accept this answer as the best.
I've been tinkering with an approach that (1) multiplies a and b with the school algorithm on 21-bit limbs (2) proceeds to do long division by c, with an unusual representation of the residual a*b - c*q that uses a double to store the high-order bits and a long to store the low-order bits. I don't know if it can be made to be competitive with standard long division, but for your enjoyment,
public class MulDiv {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
for (long i = 0; true; i++) {
if (i % 1000000 == 0) {
System.err.println(i);
}
long a = r.nextLong() >> (r.nextInt(8) * 8);
long b = r.nextLong() >> (r.nextInt(8) * 8);
long c = r.nextLong() >> (r.nextInt(8) * 8);
if (c == 0) {
continue;
}
long x = mulDiv(a, b, c);
java.math.BigInteger aa = java.math.BigInteger.valueOf(a);
java.math.BigInteger bb = java.math.BigInteger.valueOf(b);
java.math.BigInteger cc = java.math.BigInteger.valueOf(c);
java.math.BigInteger xx = aa.multiply(bb).divide(cc);
if (java.math.BigInteger.valueOf(xx.longValue()).equals(xx) && x != xx.longValue()) {
System.out.printf("a=%d b=%d c=%d: %d != %s\n", a, b, c, x, xx);
}
}
}
// Returns truncate(a b/c), subject to the precondition that the result is
// defined and can be represented as a long.
private static long mulDiv(long a, long b, long c) {
// Decompose a.
long a2 = a >> 42;
long a10 = a - (a2 << 42);
long a1 = a10 >> 21;
long a0 = a10 - (a1 << 21);
assert a == (((a2 << 21) + a1) << 21) + a0;
// Decompose b.
long b2 = b >> 42;
long b10 = b - (b2 << 42);
long b1 = b10 >> 21;
long b0 = b10 - (b1 << 21);
assert b == (((b2 << 21) + b1) << 21) + b0;
// Compute a b.
long ab4 = a2 * b2;
long ab3 = a2 * b1 + a1 * b2;
long ab2 = a2 * b0 + a1 * b1 + a0 * b2;
long ab1 = a1 * b0 + a0 * b1;
long ab0 = a0 * b0;
// Compute a b/c.
DivBy d = new DivBy(c);
d.shift21Add(ab4);
d.shift21Add(ab3);
d.shift21Add(ab2);
d.shift21Add(ab1);
d.shift21Add(ab0);
return d.getQuotient();
}
}
public strictfp class DivBy {
// Initializes n <- 0.
public DivBy(long d) {
di = d;
df = (double) d;
oneOverD = 1.0 / df;
}
// Updates n <- 2^21 n + i. Assumes |i| <= 3 (2^42).
public void shift21Add(long i) {
// Update the quotient and remainder.
q <<= 21;
ri = (ri << 21) + i;
rf = rf * (double) (1 << 21) + (double) i;
reduce();
}
// Returns truncate(n/d).
public long getQuotient() {
while (rf != (double) ri) {
reduce();
}
// Round toward zero.
if (q > 0) {
if ((di > 0 && ri < 0) || (di < 0 && ri > 0)) {
return q - 1;
}
} else if (q < 0) {
if ((di > 0 && ri > 0) || (di < 0 && ri < 0)) {
return q + 1;
}
}
return q;
}
private void reduce() {
// x is approximately r/d.
long x = Math.round(rf * oneOverD);
q += x;
ri -= di * x;
rf = repairLowOrderBits(rf - df * (double) x, ri);
}
private static double repairLowOrderBits(double f, long i) {
int e = Math.getExponent(f);
if (e < 64) {
return (double) i;
}
long rawBits = Double.doubleToRawLongBits(f);
long lowOrderBits = (rawBits >> 63) ^ (rawBits << (e - 52));
return f + (double) (i - lowOrderBits);
}
private final long di;
private final double df;
private final double oneOverD;
private long q = 0;
private long ri = 0;
private double rf = 0;
}
You can use the greatest common divisor (gcd) to help.
a * b / c = (a / gcd(a,c)) * (b / (c / gcd(a,c)))
Edit: The OP asked me to explain the above equation. Basically, we have:
a = (a / gcd(a,c)) * gcd(a,c)
c = (c / gcd(a,c)) * gcd(a,c)
Let's say x=gcd(a,c) for brevity, and rewrite this.
a*b/c = (a/x) * x * b
--------------
(c/x) * x
Next, we cancel
a*b/c = (a/x) * b
----------
(c/x)
You can take this a step further. Let y = gcd(b, c/x)
a*b/c = (a/x) * (b/y) * y
------------------
((c/x)/y) * y
a*b/c = (a/x) * (b/y)
------------
(c/(xy))
Here's code to get the gcd.
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
David Eisenstat got me thinking some more.
I want simple cases to be fast: let double take care of that.
Newton-Raphson may be a better choice for the rest.
/** Multiplies both <code>factor</code>s
* and divides by <code>divisor</code>.
* #return <code>Long.MIN_VALUE</code> if result out of range,<br/>
* else <code>factorA * factor1 / divisor</code> */
public static long
mulDiv(long factorA, long factor1, long divisor) {
final double dd = divisor,
product = (double)factorA * factor1,
a1_d = product / dd;
if (a1_d < -TOO_LARGE || TOO_LARGE < a1_d)
return tooLarge();
if (-ONE_ < a1_d && a1_d < ONE_)
return 0;
if (-EXACT < product && product < EXACT)
return (long) a1_d;
long pLo = factorA * factor1, //diff,
pHi = high64(factorA, factor1);
if (a1_d < -LONG_MAX_ || LONG_MAX_ < a1_d) {
long maxdHi = divisor >> 1;
if (maxdHi < pHi
|| maxdHi == pHi
&& Long.compareUnsigned((divisor << Long.SIZE-1),
pLo) <= 0)
return tooLarge();
}
final double high_dd = TWO_POWER64/dd;
long quotient = (long) a1_d,
loPP = quotient * divisor,
hiPP = high64(quotient, divisor);
long remHi = pHi - hiPP, // xxx overflow/carry
remLo = pLo - loPP;
if (Long.compareUnsigned(pLo, remLo) < 0)
remHi -= 1;
double fudge = remHi * high_dd;
if (remLo < 0)
fudge += high_dd;
fudge += remLo/dd;
long //fHi = (long)fudge/TWO_POWER64,
fLo = (long) Math.floor(fudge); //*round
quotient += fLo;
loPP = quotient * divisor;
hiPP = high64(quotient, divisor);
remHi = pHi - hiPP; // should be 0?!
remLo = pLo - loPP;
if (Long.compareUnsigned(pLo, remLo) < 0)
remHi -= 1;
if (0 == remHi && 0 <= remLo && remLo < divisor)
return quotient;
fudge = remHi * high_dd;
if (remLo < 0)
fudge += high_dd;
fudge += remLo/dd;
fLo = (long) Math.floor(fudge);
return quotient + fLo;
}
/** max <code>double</code> trusted to represent
* a value in the range of <code>long</code> */
static final double
LONG_MAX_ = Double.valueOf(Long.MAX_VALUE - 0xFFF);
/** max <code>double</code> trusted to represent a value below 1 */
static final double
ONE_ = Double.longBitsToDouble(
Double.doubleToRawLongBits(1) - 4);
/** max <code>double</code> trusted to represent a value exactly */
static final double
EXACT = Long.MAX_VALUE >> 12;
static final double
TWO_POWER64 = Double.valueOf(1L<<32)*Double.valueOf(1L<<32);
static long tooLarge() {
// throw new RuntimeException("result too large for long");
return Long.MIN_VALUE;
}
static final long ONES_32 = ~(~0L << 32);
static long high64(long factorA, long factor1) {
long loA = factorA & ONES_32,
hiA = factorA >>> 32,
lo1 = factor1 & ONES_32,
hi1 = factor1 >>> 32;
return ((loA * lo1 >>> 32)
+loA * hi1 + hiA * lo1 >>> 32)
+ hiA * hi1;
}
(I rearranged this code some out of the IDE to have mulDiv() on top.
Being lazy, I have a wrapper for sign handling - might try and do it properly before hell freezes over.
For timing, a model of input is in dire need:
How about such that each result possible is equally likely?)
Perhaps not clever, but has linear result time
#define MUL_DIV_TYPE unsigned int
#define BITS_PER_TYPE (sizeof(MUL_DIV_TYPE)*8)
#define TOP_BIT_TYPE (1<<(BITS_PER_TYPE-1))
//
// result = ( a * b ) / c, without intermediate overflow.
//
MUL_DIV_TYPE mul_div( MUL_DIV_TYPE a, MUL_DIV_TYPE b, MUL_DIV_TYPE c ) {
MUL_DIV_TYPE st, sb; // product sum top and bottom
MUL_DIV_TYPE d, e; // division result
MUL_DIV_TYPE i, // bit counter
j; // overflow check
st = 0;
sb = 0;
d = 0;
e = 0;
for( i = 0; i < BITS_PER_TYPE; i++ ) {
//
// Shift sum left to make space
// for next partial sum
//
st <<= 1;
if( sb & TOP_BIT_TYPE ) st |= 1;
sb <<= 1;
//
// Add a to s if top bit on b
// is set.
//
if( b & TOP_BIT_TYPE ) {
j = sb;
sb += a;
if( sb < j ) st++;
}
//
// Division.
//
d <<= 1;
if( st >= c ) {
d |= 1;
st -= c;
e++;
}
else {
if( e ) e++;
}
//
// Shift b up by one bit.
//
b <<= 1;
}
//
// Roll in missing bits.
//
for( i = e; i < BITS_PER_TYPE; i++ ) {
//
// Shift across product sum
//
st <<= 1;
if( sb & TOP_BIT_TYPE ) st |= 1;
sb <<= 1;
//
// Division, continued.
//
d <<= 1;
if( st >= c ) {
d |= 1;
st -= c;
}
}
return( d ); // remainder should be in st
}
Divide a/c and b/c into whole and fractional (remainder) parts, then you have:
a*b/c
= c * a/c * b/c
= c * (x/c + y/c) * (z/c + w/c)
= xz/c + xw/c + yz/c + yw/c where x and z are multiples of c
As such, you can trivially calculate the first three factors without overflow. In my experience, this is often enough to cover typical overflow cases. However, if your divisor is too large, such that (a % c) * (b % c) overflows, this method still fails. If that's a typical issue for you, you may want to look at other approaches (e.g. dividing both the biggest of a and b as well as c by 2 until you have no overflows anymore, but how to do that without introducing additional error due to biases in the process is non-trivial -- you'll need to keep a running score of the error in a separate variable, probably)
Anyway, the code for the above:
long a,b,c;
long bMod = (b % c)
long result = a * (b / c) + (a / c) * bMod + ((a % c) * bMod) / c;
If speed is a big concern (I'm assuming it is at least to some extent, since you're asking this), you may want to consider storing a/c and b/c in variables and calculating the mod through multiplication, e.g. replace (a % c) by (a - aDiv * c) -- this allows you to go from 4 divisions per call to 2.

efficient algorithm for Pythagorean Triples in java

So I try to make a program using java.
its input is integers, the integers are considered as the sum of 3 integers a, b and c (a^2 + b^2 = c^2), its output is c^2. To do this, I expand the equation combine a^2 + b^2 - c^2 = 0 and c = sum - a - b, get Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b. Then I get a + b <= sum*2/3 then I substitute all the combination of a, b into the equation to see when it is zero.
Here is my code:
/** Pythagorean Triples
* test case for small numbers
* Tony
*/
import java.util.*;
public class Solution54 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
for (int i = 0; i < times; i++) {
/* prompt the sum and get the equation:
* Math.pow(sum, 2) - 24 * (a + b) + 2a*b = 0;
* we consider b >= a;
*/
double sum = sc.nextDouble();
double ablimits = Math.floor(sum / 3 * 2); // a + b <= ablimits
double alimits = Math.floor(ablimits / 2); // a <= alimits
//System.out.println("another round");
//System.out.print(alimits + " " + blimits);
A: for (double a = 1; a <= alimits; a++) {
B: for (double b = a; b <= sum - a; b++) {
double result = Math.pow((sum-a-b),2)-a*a-b*b;
//System.out.print("when a is " + a + " " + "when b is " + b + ":" + result + ";");
if (Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b == 0) {
double answer = a*a + b*b;
int output = (int)answer;
System.out.print(output + " ");
break A;
}
}
}
}
}
}
When I input 1 12 , it gives 25(because a,b,c=3,4,5; c^2 = 25), but it can't handle big inputs like 14808286 because my algorithm is not efficient enough. What is the efficient way to do this? Plz!
Let me preface this by saying I don't have intimate knowledge of Pythagorean triples or the math behind them. I just thought this was an interesting problem, so I gave it a stab.
I believe the key to this problem is knowing what you're looking for as you scan through possible values of a. Given
a + b + c = sum
and
a^2 + b^2 = c^2
you'll find that
b = (sum / 2) * (1 - (a / (sum - a)))
= (sum / 2) - ((a * sum) / (2 * (sum - a)))
You know that b must be a whole number. An interesting property of Pythagorean triples is that their sums are always even. That means that
(sum / 2) % 1 = 0
So all we really need to check to make sure b is valid (i.e. a whole number) is that
((a * sum) / (2 * (sum - a))) % 1 = 0
or, put more simply,
(a * sum) % (sum - a) = 0
Some other key points that simplify this problem, at least as you've stated it:
Once you have a, b can be computed using the third equation in this answer.
Once you have a and b, c follows easily from either of the Pythagorean triple equations.
You only need to print c^2 as your output. Once this is done you can break.
The code ends up being pretty simple:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get the sum from System.in.
int sum = sc.nextInt();
// If the given sum is odd, return immediately.
// No Pythagorean triple will have an odd sum.
if ((sum ^ 1) == 1) {
return;
}
// Try all values of a within the expected bounds.
int aBound = sum / 2;
for (int a = 1; a < aBound; a++) {
// Check whether b would be a whole number with this value of a.
if ((a * sum) % (a - sum) == 0) {
int b = (sum * (2 * a - sum)) / (2 * a - 2 * sum);
int c = sum - a - b;
System.out.println((int)Math.pow(c, 2));
break;
}
}
}
It's worth noting that because I lack deep mathematical understanding of Pythagorean triples, there's very likely some further optimization that can be done in deciding which values of a actually need to be checked. I imagine there's some mathematical criteria for that.
I hope this helps!

Need Help Finding the intersection of two equations in Java

I saw someone else posted this problem but didn't word it properly so he didn't end up receiving any help, so I figured I would try and be more direct.
Here is the problem proposed to us :
// Write and submit your code in a file called Intersect.java. Use the IO module to read inputs. Use System.out.println() to print your answer.
Write a program that calculates the intersection between 2 equations:
a degree-2 (quadratic) polynomial i.e.
y = dx^2 + fx + g
where d, f, and g are constants
and a degree-1 (linear) equation i.e.
y = mx + b
where m is the slope and b is a constant
The above is just text, not code that could appear in a Java program.
Ask the user for the constant values in each equation. Output the intersection(s) as ordered pair(s) (x,y), or "none" if none exists. Below is an example run.
java Intersect
Enter the constant d:
5
Enter the constant f:
-3
Enter the constant g:
2
Enter the constant m:
1
Enter the constant b:
3
The intersection(s) is/are:
(1,4)
(-0.20,2.8)
//
The main problem is essentially asking us to write a code that asks the user to imput the individual constants and the slope of the two equations, one being a quadratic polynomial and the other being a linear equation in point-slope.
I understand that we have to use the quadratic equation in the code, however I have no idea how to actually code this in.
Once we have had the user imput the constants, in this case 5 (d,f,g,m,b; with m being slope) we need to have the code run the calculations to imput those constants into the above example ( y = dx^2 + fx + g | y = mx + b) and return either "none" if there is no intersection, or if it does intersect, the ordered pair at which it does intersect (x,y).
I know already that if 0 is entered as the constants it returns (NaN,NaN) which I also know needs to be re-written to None.
so far I only have the following:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
If anyone can shed some light on this that would be fantastic, thanks!
EDIT1 :
So far i've changed the code to the following, however, I still don't know how to get it to return to me an answer:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
int A = d;
int B = f - m;
int C = g - b;
double x1 = - B + Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double x2 = - B - Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double y1 = m * x1 + b;
double y2 = m * x1 + b;
}
Also, eclipse is telling me that x2,y1, and y2 aren't used at all.
I know I need to use System.out.println() however I don't understand what I can put there to make the answer an ordered pair. Also, I tried setting an If statement to have the answer return None instead of NaN however it instead returns, NaN None.
There are a lot of special cases you have to take into account.
I hope I've got them all right.
So after the initialization of the values you can put this:
// calculating some useful values.
double t = -(f - m) / (2.0 * d);
double u = t * t - (g - b) / (double) d;
// the first polynomial is linear, so both terms are.
if (d == 0) {
// both linear functions have the same slope.
if (f == m) {
// both functions are shifted the same amount along the y-Axis.
if (g == b)
// the functions lie on top of each other.
System.out.println("There is an infinite amount intersections");
// the functions are shifted different amounts along the y-Axis.
else
// the lines are parallel.
System.out.println("There are no intersections");
}
// both linear functions have different slopes.
else {
// solve linear equation.
double x = (b - g) / (double) (f - m);
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
}
// the functions do not cross each other.
else if (u < 0)
System.out.println("There are no intersections");
// the linear function is a tangent to the quadratic function.
else if (u == 0) {
// solve equation.
double x = t;
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
// the linear function intersects the quadratic function at two points.
else {
// solve quadratic equation.
double x1 = t + Math.sqrt(u);
double x2 = t - Math.sqrt(u);
double y1 = m * x1 + b;
double y2 = m * x2 + b;
System.out.println("The intersections are: (" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ")");
}
i guess....
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
A = d
B = f - m
C = g - b
x1 = - B + sqr( B^2 - 4 * A * C ) / (2 * A)
x2 = - B - sqr( B^2 - 4 * A * C ) / (2 * A)
y1 = m * x1 + b
y2 = m * x1 + b

Why won't this quadratic equation return negative numbers?

This quadratic equation will not return negative numbers in the string that I've determined it to return.
Here's the equation:
public class QuadraticEquation {
String final0;
public String calculate(int a, int b, int c) {
double done1 = ((-1 * b) + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
double done2 = ((-1 * b) - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
}
imagine an equation with a, b, and c values like -3, 13, and -4. The returning value of this would be -0.3(repeating) and -4. But this equation only returns positives, so in this case it would return 0.3(repeating) and 4. Why is this, and what can I do to fix it?
Note: I do believe that this is a Java error and not a math error. If it is a math error, let me know in the comments and I will promptly put it in the proper forums. Thanks.
public static void main(String[] args) {
String final0 = calculate(-3, 13, -4);
System.out.println(final0);
}
public static String calculate(int a, int b, int c) {
String final0 ;
int i = -1 * b; // -1 * 13 = -13
System.out.println(i);
int j = 4 * a * c; // 4 * -3 * -4 = 4 * 12 = 48
System.out.println(j);
double sqrt = Math.sqrt((b * b) - j); // sqrt ((13 * 13) - 48) = sqrt(169 - 48) = sqrt(121) = 11
System.out.println(sqrt);
double d = i + sqrt; // -13 + 11 = -2
System.out.println(d);
int k = 2 * a; // 2* -3 = -6
System.out.println(k);
double done1 = d / k; // -2 / -6 = 1/3 = 0.3333333333
System.out.println(done1);
double done2 = (i - sqrt) / k;
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
If you decompose your method to more local variables, you will see that math in java works correctly.
I would have thought
-3*x^2 + 13 *x + -4 = -3 * (x - 0.33333) * (x - 4) = 0
so two positive answers is correct.
Try instead
1 * x^2 + 0 * x -1 = (x - 1) * (x + 1) = 0
i.e. x = -1 or +1
Here is how I would write it.
public static String calculate(int a, int b, int c) {
double sqrt = Math.sqrt((b * b) - (4 * a * c));
double done1 = (-b + sqrt) / (2 * a);
double done2 = (-b - sqrt) / (2 * a);
return "x = " + (done1) + " or x = " + (done2);
}
The code is working correctly with your input. If you changed b to be -13 for example, you would get
x = -4.0 or x = -0.3333333333333333
Math.sqrt will always return a positive number ignoring complex numbers. But that is somewhat besides the point.

Modular inverse - java coding

Please help. I've been working on this non stop and can't get it right. The issue I'm having is that the output I'm getting for the inverse is always 1.
This is the code that I have (it computes GCD and trying to modify so it also computes a^-1):
import java.util.Scanner;
public class scratchwork
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
long n, a, on, oa;
long gcd = 0;
System.out.println("Please enter your dividend:");
n= keyboard.nextLong();
System.out.println("Please enter your divisor:");
a= keyboard.nextLong();
on= n;
oa= a;
while (a!= 0)
{gcd=a;
a= n% a;
n= gcd;
}
System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);
long vX; vS; vT; vY; q; vR; vZ; m; b;
vX = n; vY=a;
vS = 0; vT = 1; m=0; b=0;
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
if (d>1) System.out.println("Inverse does not exist.");
else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
}
}
The code you've posted does not declare most of the variables it uses and thus dues not compile. Most importantly, the variable v it uses to output the result is neither defined nor assigned to anywhere in the posted code - whatever it contains has nothing to do with the calculation.
Can we see the variables declaration? If you mix integer with double, your numbers can be rounded. Anyway, if you only want the inverse, juste use Math.pow(a, -1);
Also, in the second loop, you never set "a" so it will loop forever:
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
#Justin,
Thanks. I was able to figure out how to print out the variables in each loop. I basically had to put my loop up with the GCD loop...that was it. 2 weeks worth of work and I had just to move where the loop was.
It works! I'm sorry but I'm doing a happy dance over here.
Here's a solution in Python that should be easily translatable into Java:
def euclid(x, y):
"""Given x < y, find a and b such that a * x + b * y = g where, g is the
gcd of x and y. Returns (a,b,g)."""
assert x < y
assert x >= 0
assert y > 0
if x == 0:
# gcd(0,y) = y
return (0, 1, y)
else:
# Write y as y = dx + r
d = y/x
r = y - d*x
# Compute for the simpler problem.
(a, b, g) = euclid(r, x)
# Then ar + bx = g -->
# a(y-dx) + bx = g -->
# ay - adx + bx = g -->
# (b-ad)x + ay = g
return (b-a*d, a, g)
def modinv(x, n):
(a, b, g) = euclid(x%n, n)
assert g == 1
# a * x + b * n = 1 therefore
# a * x = 1 (mod n)
return a%n
It uses the stack, but Euclid's algorithm takes O(log n) steps so you won't have a stack overflow unless your numbers are astronomically high. One could also translate it into a non-recursive version with some effort.

Categories

Resources