I am currently attempting this question :
A Pythagorean triplet is a set of three natural numbers, a, b and c, for which
a2 + b2 = c2.
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My code is as follows, I think it should be correct, but the site is telling me my answer is wrong? Can someone help me see the flaws in my logic please?
public class Pythagoras {
public static void main(String[] args) {
int sum = 1000;
int a;
int product=0;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( c > 0 && (a*a + b*b == c*c) )
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
}
System.out.println(product);
}
}
Here are 5 solutions (from slow to fast):
1) Trivial implementation - 732857 microseconds (0.7 seconds)
private static void p1(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = 0; b <= sum; b++) {
for (int c = 0; c <= sum; c++) {
if (a < b && b < c && a + b + c == sum
&& (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
2) Limit the lower bound for b & c (establish the order relation) - 251091 microseconds (0.2 seconds)
private static void p2(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum; b++) {
for (int c = b + 1; c <= sum; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
3) Limit the lower & upper bounds for b & c - 111220 microseconds (0.1 seconds)
private static void p3(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
for (int c = b + 1; c <= sum - a - b; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
4) Limit lower & upper bounds for b and fix value for c - 2625 microseconds
private static void p4(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
int c = sum - a - b;
if (c > b && c * c == a * a + b * b) {
System.out.print(a * b * c);
return;
}
}
}
}
5) Use Euclid's formula - 213 microseconds
private static void p5(int sum) {
// a = m^2 - n^2
// b = 2mn
// c = m^2 + n^2
int a, b, c;
int sqrt = (int)Math.sqrt(sum);
for (int n = 1; n <= sqrt; n++) {
for (int m = n+1; m <= sqrt; m++) {
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
if ( a + b + c == 1000 ) {
System.out.print(a * b * c);
return;
}
}
}
}
I think you're missing a set of braces. The indentation leads me to believe the two innermost statements go together but you need curly braces for that to be correct.
if ( c > 0 && (a*a + b*b == c*c) )
{
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
Without the braces product will always contain the product of the last values of a, b, and c. (333 * 500 * 167 == 27805500).
Though others have already given specific fixes for you code, here's a more general hint that will be useful on other problems as well. Test your code on a simpler version of the problem.
For example, see if your program can find 6,8,10 as a triplet with a sum of 24. With a smaller test you can actually step through the code to see where it's going wrong.
You may try it this way,
public class Pythagoras {
public static void main(String[] args) {
int m = 1, n = 0, a = 0, b = 0, c = 0, sum = 0;
int product = 0;
for (m = 2; m < 100; m++) {
for (n = 1; n < 100; n++) {
while (m > n) {
a = (m * m) - (n * n);
b = (2 * m) * n;
c = (m * m) + (n * n);
sum = a + b + c;
if (sum == 1000) {
product = a * b * c;
System.out.print("a :" + a + "b :" + b + "c : " + c);
System.out.println("Product is" + product);
break;
}
break;
}
}
}
}
}
This implements the Euclid's formula for generating Pythagorean triplet as explained here
Note that in this method we make only triplets hence unwanted repetitions are reduced.
and the output is a :375 b :200 c : 425 Product is 31875000
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public javax.swingx.event.*;
public class Triplet extends JApplet implements ActionListener
{
JLabel l1, l2, l3;
JButton b1;
JTextFiel t1, t2;
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
l1=new JLabel("Enter the value of a: ");
l2=new JLabel("Enter the value of b: ");
t1 = new JTextField(20);
t2 = new JTextField(20);
b1=new JButton("Ok");
l2=new JLabel(" ");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
b1.addActionListener(this);
public void ActionPerformed(ActionEvent e)
{
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
long c = Math.sqrt(a*a + b*b);
l3.setText(" " +c);
}
}
}
public class Pythagorean_Triplets
{
public static void main(long n)
{
long h=1,p=1,b1;
double b;
while(h<=n)
{
while(p<h)
{
b=Math.sqrt((h*h)-(p*p));
if(b%1==0)
{
b1=(long)b;
System.out.println(b1+","+p+","+h);
break;
}
p++;
}
h++;
p=1;
}
}
}
Related
public class Pow {
public double getAnswer(double a, double b) {
double b2 = 0;
if (b > 0) {
for (int i = 1; i < b; i++) {
a = a * a;
}
return a;
} else if (b < 0) {
int c = 0;
while (c > b) {
a = a * a;
c--;
}
b2 = 1 / a;
}
return b2;
}
}
I need the second part of my method to return the value of a negative power(i.e. 5^-2 = .04), but the output is always 0. The first part of the method works fine from what I have tested. I do have the last curly braces but they just wouldn't fit in the text box on here. Any help/suggestions would be much appreciated!
Running your code does not produce 0 as a result, but there is a bug.
a = a * a squares the number every iteration, so an will be calculated as: a2n-1.
Try accumulating the multiplication in a different variable:
double b2 = 0;
double result = 1;
if (b > 0) {
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
} else if (b < 0) {
int c = 0;
while (c > b) {
result *= a;
c--;
}
b2 = 1 / result;
}
return b2;
public class Pow {
public double getAnswer(double a, double b) {
double b2 = 0;
if (b > 0) {
for (int i = 1; i < b; i++) {
a = a * a;
}
return a;
} else if (b < 0) {
return getAnswer(a, -b);
}
return 1; // b is 0
}
Your algorithm for (b < 0) was wrong. If b < 0, the calculation is 1 / a^(-b).
Why your parameter b is of type double? What if b is 2.5? I suggest to change the type of b to int or you have to change your algorithm.
As Bohemian♦ said
a = a * a;
squares a each time.
What we want is for a (the base) to be multiplied by itself b (the power) times.
Since the only difference between a to the power of b and a to the power of (-b) is that the latter is the 1 / the former, we can use quite nearly the same code for both negative and positive exponents.
Code:
public double getAnswer(double a, double b) {//a is the base, b is the power
double a2 = 1;
double b2 = 0;
if (b > 0) {//for positive powers
for (int i = 0; i < b; i++) {//a needs to be multiplied by itself (b) times
a2 = a2 * a;
}
return a2;
}
else if (b < 0) {//for negative powers
for (int i = 0; i < -b; i++) {//a still needs to be multiplied by itself (-b) times, but since b is negative, we increment up to the opposite of b
a2 = a2 * a;
}
return 1 / a2;//finally, since the power (b) is negative, we need to return 1 / (a2)
}
}
I want to print the result the same way that i print the numbers that i use.
for ex i print 1,2,3,4 2,3,4,5 but the pow remains the same 1024,1024,1024,1024.
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
d = a;
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
}
}
for (int a = 1, b = 2; a < 5; a++, b++) {
d = a;
e = b;
System.out.println(d + " " + e + " " + c);
}
}
This should work, and is also more readable.(you really ought to indent code properly).
Your problem is in the loop logic.
What you are doing is probably possible with for loops, but i think a while loop with two conditionals would work nice.
int a = 1;
int b = 2;
double c = 0.0;
while (a < 5 && b < 6){
c=java.lang.Math.pow (a,b);
System.out.println ( a+ " " +b +" " + c);
b++;
a++;
}
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
System.out.println(a + " " + b + " " + c);
}
}
}
If I understood your problem try something like this output should be ok
So I need help calculating Pythagorean Triples, basically I want the output to look like this:
3 4 5
5 12 13
6 8 10
7 24 25
ETC.
I need help with the calculation portion and to ensure that I do not have duplicates (i.e. 5 12 13 and 12 5 13).
Thoughts? Can someone lead me in the right direction?
Here is my code that I have so far:
package cs520.hw1;
public class Triples {
public static void main(String[] args)
{
int x1, x2, x3;
for(x1 = 1; x1 < 100; x1++)
{
for(x2 = 1; x2 < 100; x2++)
{
for(x3 = 1; x3 < 100; x3++)
{
int a= x1, b=x2, c=x3;
if((Math.sqrt(a) + Math.sqrt(b)) == Math.sqrt(c))
{
if(a < b)
{
System.out.println(x1 +" "+ x2 +" "+ x3);
}
}
}
}
}
}
}
Example code:
public class QuickTester {
// Change MAX to whatever value required
private static final int MAX = 25;
public static void main(String[] args) {
int a, b, c;
for(a = 1; a < MAX; a++)
{
for(b = a; b < MAX; b++)
{
for(c = b; c < MAX; c++)
{
if((Math.pow(a, 2) + Math.pow(b, 2))
== Math.pow(c, 2))
{
System.out.printf("%d %d %d\n",
a, b, c);
}
}
}
}
}
}
Output (for MAX being 25 instead of 100):
3 4 5
5 12 13
6 8 10
8 15 17
9 12 15
12 16 20
Note:
To ensure that you don't get (5 12 13 and 12 5 13), simply make sure that a < b < c.
Use (Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2) to find the triplets
You need to change the calls to Math.sqrt(n) to Math.pow(n, 2), where n = a, b, c.
So, the code becomes
package cs520.hw1;
public class Triples {
public static void main(String[] args)
{
int x1, x2, x3;
for(x1 = 1; x1 < 100; x1++)
{
for(x2 = 1; x2 < 100; x2++)
{
for(x3 = 1; x3 < 100; x3++)
{
int a= x1, b=x2, c=x3;
if((Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2))
{
if(a < b)
{
System.out.println(x1 +" "+ x2 +" "+ x3);
}
}
}
}
}
}
}
public class Triplets {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a, b, c;
System.out.println("Enter the value of n: ");
int n = in.nextInt();
System.out.println("Pythagorean Triplets upto " + n + " are:\n");
for (a = 1; a <= n; a++) {
for (b = a; b <= n; b++) {
for (c = 1; c <= n; c++) {
if (a * a + b * b == c * c) {
System.out.print(a + ", " + b + ", " + c);
System.out.println();
}
else
continue;
}
}
}
}}
I appreciate the help. I was able to finish modifying everything in this class into BigInteger format except for the compose method. Can anyone help me with this last part as to why it is not working correctly? I really appreciate it, thanks.
import java.math.BigInteger;
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = new BigInteger("1");
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = new BigInteger("1");
coef[0] = new BigInteger(Integer.toString(a));
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
for(int i = 0; i < b; i++){
if(coef[i] == null)
coef[i] = new BigInteger("0");
}
coef[b] = new BigInteger(Integer.toString(a));
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i] != null) d = i; // check to make sure this works
return d;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, 0);
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i].intValue(), 0);
c = term.plus(b.times(c));
}
return c;
}
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add((a.coef[i].multiply(b.coef[j])));
c.deg = c.degree();
return c;
}
/** Return a textual representation of this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return coef[1] + "x + " + coef[0];
String s = coef[deg] + "x^" + deg;
for (int i = deg-1; i >= 0; i--) {
if (coef[i] == null) continue;
else if (coef[i].intValue() > 0) s = s + " + " + ( coef[i]);
else if (coef[i].intValue() < 0) s = s + " - " + (coef[i].negate());
if(coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial p = new Polynomial(1,2);
Polynomial q = new Polynomial(2,3);
Polynomial t = p.compose(q); // incorrect
System.out.println("p(q(x)) = " + t); // incorrect
}
}
What I think is the problem is with your toString() itself as it does not align to your defaulting mechanism. Meaning, you assign default value of '0's but do not check for 0 values in the following lines:
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
It gets piled up even for 0 coefficient values. Add a condition of checking non-zero coefficient only:
if (coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
This should work, I haven't tested it but you can try testing and post the results.
EDIT:
Well, i just tried your code and seems to give the correct information with the above condition in place:
6x^7 + 2x^3
What's wrong with my code? It prints 2,2 when the correct answer is clearly 6,8
public static void main(String[] args) {
int a = 1;
int b = 1;
int answer = 0;
int j = 4;
while (j == 4) {
for (a = 1; a <= 10; a++) {
for (b = 1; b <= 10; b++) {
answer = a * a + b * b;
if (answer == 100) {
j = 10;
}
}
}
}
System.out.println(a + " " + b);
}
if(answer == 100);
you have an extra semicolon after your if.
This will cause it to execute the j = 10; no matter what answer equals
You are incrementing a and b at the same time. In your code, the two numbers will always be equal. Also, you are not testing for a match when you exit the loop.