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!
Related
I am in a Java class and it's still early in the class. The assignment is to:
e^x Approximations
The value ex can be approximated by the following sum:
1 + x + x^2/2! + x^3/3! + …+ x^n/n!
The expression n! is called the factorial of n and is defined as: n! = 1*2*3* …*n.
Write a program that takes a value of x as input and outputs four approximations of ex done using four different values of n: 5, 10, 50, and 100. Output the value of x the user entered and the set of all four approximations into the screen.
Sample formula use: calculating e^7 using approximation with n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
I've got all the rest to work, including getting n to be 5, 10, 50 and 100. I thought I had the factorial formula figured out and I used the number 4 like the sample we were show and my numbers done match. Could really use another set of eyes.
Here's my code with forumla (x is the value the user enters and n is the 5, 10, 50 and 100):
/**
* myFact takes in x and calculates the factorial
* #param x
* #param n
* #return the factorial as a long
*/
public static long myFact(int x, int n) {
//declare variables
long sum = x;
for (int i=2; i <= n; i++) {
sum += ((Math.pow(x, i))/i);
}
return (sum + 1);
}
}
Here's the main class where I am calling the function. The error I suppose could be there too:
public static void main(String[] args) {
//declare variable for user input and call method to initialize it
int x = getNumber();
long fact;
int n;
//Output first line
System.out.println("N\t approximate e^" + x);
for (n = 5; n <= 100; n *= 2) {
if (n == 10) {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
n += 15;
} else {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
}
}
}
Thanks for taking a look at this, it's taken me hours to get this as the teacher gave us very little help.
You did a mistake in
sum += ((Math.pow(x, i))/i);
here you need to calculate the i!. Add below method in your code
public static int fact(int i){
int fact = 1;
for (int n = i; n > 0; n--) {
fact = fact * n;
}
return fact;
}
Also change sum += ((Math.pow(x, i))/i) to
sum += ((Math.pow(x, i))/fact(i));
How to make the method roots check imaginary roots and real one then return their values?
package warmup;
import java.util.HashSet;
import java.util.Set;
public class Quadratic {
/**
* Find the integer roots of a quadratic equation, ax^2 + bx + c = 0.
* #param a coefficient of x^2
* #param b coefficient of x
* #param c constant term. Requires that a, b, and c are not ALL zero.
* #return all integers x such that ax^2 + bx + c = 0.
*/
public static Set<Integer> roots(int a, int b, int c) {
Set<Integer> z = new HashSet<>();
int temp1 = (int)(Math.sqrt(b*b - 4*a*c));
if(a !=0){
if(temp1 >= 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
} else if (temp1 < 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
}
}else{
System.out.println("Error: division by zero.");
}
return z;
}
/**
* Main function of program.
* #param args command-line arguments
*/
public static void main(String[] args) {
System.out.println("For the equation x^2 - 4x + 3 = 0, the possible solutions are:");
Set<Integer> result = roots(1, -4, 3);
System.out.println(result);
}
trying to assign a negative square root number value to java is not allowed in JDK.
what you can do is, you can create a complex number class of your own and do your own operations there. Here is the example which i found online:
http://introcs.cs.princeton.edu/java/97data/Complex.java.html
I also looked at SO for similar questions like yours and i got this link
Hope this helps
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.
I was attempting to solve this morning's Codeforces problem Div 2C: http://codeforces.com/contest/716/problem/C
This problem has the potential to loop up to 100,000 times so the parameter here can be up to 100,000. Loop seems to break when passing in 100,000 (and possibly earlier) and i is declared as an int:
public void solve(int a) {
double x = 2;
double y = 0;
double n = 0;
double target = 0;
double lcm = 0;
for (int i = 1; i <= a; i++) {
lcm = (i + 1) * i;
y = ((lcm * lcm) - x) / i;
n = (y * i) + x;
if (Math.sqrt(n) % (i + 1) == 0) {
x = Math.sqrt(n);
String answer = String.format("%.0f", y);
System.out.println("this is i: " + i);
System.out.println(answer);
}
}
}
Here is the relevant output:
this is i: 46337
99495281029892
this is i: 46338
99501722706961
this is i: 46340
99514606895203
this is i: 65535
32769
Doing a quick search on Stack overflow shows that the number 65535 is associated with a 16-bit unsigned int, but java uses 32bit ints. Changing the type to double works, as does simply looping 100,000 times and printing without the code logic. I understand that 100,000^2 IS above the maximum int limit, but this value is never stored as an int in my code. What's going on here?
The following line generates an out of bounds int before converting the result to double:
lcm = (i + 1) * i;
The above is essentially the same as:
lcm = (double)((i + 1) * i);
or
int temp = (i + 1) * i;
lcm = (double) temp;
Instead try (first converting to double and then taking what is similar to a square):
lcm = (i + 1.0) * i;
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