Pythagorean Triples Calculation for Java - java

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;
}
}
}
}}

Related

How can I output the points that are colinear?

THE PROBLEM: Write a program that reads N points in a plane and outputs any group of four or more colinear points
What I did: I calculated the slope of every 2 points and then put them in a hashmap to see which one is the max.
What I need to do: I need to output the points that are colinear from the initial 2D array. I found the number of points that are colinear with the hashmap.
import java.util.*;
public class app {
public static int maxPoints(int[][] points) {
int ans = 1;
int n = points.length;
for (int i = 0; i < n; i++) {
HashMap<String, Integer> map = new HashMap<>();
int OLP = 0;
int max = 0;
for (int j = i + 1; j < n; j++) {
if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {
OLP++;
continue;
}
int dy = points[j][1] - points[i][1];
int dx = points[j][0] - points[i][0];
int g = gcd(Math.abs(dy), Math.abs(dx));
int num = dy / g;
int deno = dx / g;
if (num == 0)
deno = 1;
if (deno == 0)
num = 1;
if ((num < 0 && deno < 0) || deno < 0) {
num *= -1;
deno *= -1;
}
map.put(createString(deno, num), map.getOrDefault(createString(deno, num), 0) + 1);
max = Math.max(max, map.get(createString(deno, num)));
}
ans = Math.max(ans, 1 + OLP + max);
}
return ans;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return a;
int max = Math.max(a, b);
int min = Math.min(a, b);
return gcd(max % min, min);
}
public static String createString(int a, int b) {
return Integer.toString(a) + " " + Integer.toString(b);
}
public static void main(String[] args) {
int[][] points = { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 4 } };
System.out.println("max Points are: " + maxPoints(points));
}}

Can I solve this problem with Dynamic Programming?

How I find among all pairs a and b with a "least common multiple" LCM(a,b) = 498960 and a "greatest common divisor" GDM(a, b) = 12 a pair with minimum sum a + b?
I solved this with O(n^2) time:
public class FindLcmAndGcdClass {
private int findGcd(int a, int b) {
if (a % b == 0) {
return b;
}
return findGcd(b, a % b);
}
private int findLcm(int a, int b, int gcd) {
return (a * b) / gcd;
}
private void run() {
int minSum = Integer.MAX_VALUE;
int foundNumberOne = 0;
int foundNumberTwo = 0;
for (int i = 12; i <= 498960; i += 12) {
for (int j = i; j <= 498960; j += 12) {
int gcd;
if (i < j) {
gcd = findGcd(j, i);
} else {
gcd = findGcd(i, j);
}
int lcm = findLcm(i, j, gcd);
if (gcd == 12 && lcm == 498960 && i + j < minSum) {
minSum = i + j;
foundNumberOne = i;
foundNumberTwo = j;
}
}
}
System.out.println(minSum);
System.out.println(foundNumberOne);
System.out.println(foundNumberTwo);
}
public static void main(String[] args) {
var o = new FindLcmAndGcdClass();
o.run();
}
}
And it executes quite slowly! I guess the problem can be solved with Dynamic Programming. Can anyone help with more fast solution?
I am not sure if this question can be solved with dynamic programming, but I think of a solution with time complexity O(sqrt(LCM * GCD)).
It is well known that for any two integers a and b, LCM(a, b) * GCD(a, b) = a * b. Therefore, you can first calculate the product of the gcd and lcm, (which is 5987520 in this question). Then for all its factors under sqrt(LCM * GCD), let a be one of the factors, then b = LCM * GCD / a. Test if gcd(a, b) = the required gcd, if so calculate the sum a + b, then find the minimum among the sums, and you are done.

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Finding Two Bases Which When Converted to Base 10 Are Equal

I have a very challenging problem here today. I cannot think of a way to solve it.
Given 6 numbers as input: a1, a2, a3, b1, b2, b3, find 2 numbers X and Y such that a1 * x^2 + a2 ^ x + a3 = b1 * y^2 + b2 * y + b3. X and Y must be between 10 and 15000 inclusive.
What I have tried:
I have tried all X values from 10-15000 and all Y values from 10-15000, and checked if they satisfied the equation. However, this method is extremely slow. Does anyone have a faster solution? Thanks.
My Bad Code:
for (int i = 0; i < k; i++) {
int a, b;
cin >> a >> b;
for (int i = 10; i <= 15000; i++) {
for (int j = 10; j <= 15000; j++) {
if (conv(a, i) == conv(b, j)) {
cout << i << " " << j << endl;
j = 20000;
i = 20000;
}
}
}
}
long long conv(int x, int b) {
long long ans = 0;
int count = 0;
while (x) {
int y = x % 10;
ans += y * poww(b, count);
count++;
x /= 10;
}
return ans;
}
long long poww(int x, int y) {
long long ans = 1;
while (y != 0) {
ans *= x;
y--;
}
return ans;
}
I thought this might be a good occassion to exercise writing some Java code and came up with the following solution. On my system it gives the solution to the two numbers 419 and 792 (as you wrote in an earlier edit of your question the result should be Base X: 47 Base Y: 35) in 1 ms.
The code just uses some smart brute force :).
See it running online.
public class TwoBases {
public static void main(String[] args) {
long beg = System.nanoTime();
solve(419, 792);
System.out.println("Time needed to calculate: "+(System.nanoTime()-beg)/1000000.0 + "ms");
}
public static void solve(int a, int b) {
int[] aDigits = new int[3];
int[] bDigits = new int[3];
for (int i = 0; i < 3; i++) {
aDigits[2 - i] = (a / (int) Math.pow(10, i)) % 10;
bDigits[2 - i] = (b / (int) Math.pow(10, i)) % 10;
}
for (int x = 10; x <= 15000; x++) {
int numBaseX = digitsToBase10(aDigits, x);
int y = 10;
while (y <= 15000) {
int numBaseY = digitsToBase10(bDigits, y);
if (numBaseX == numBaseY) {
System.out.println("Base X: " + x + " Base Y: " + y);
return;
} else if (numBaseY > numBaseX) {
break;
} else {
y++;
}
}
}
System.out.println("Nothing found");
}
public static int digitsToBase10(int[] digits, int b) {
int res = 0;
for (int i = 0; i < digits.length; i++) {
res += digits[i] * (int) Math.pow(b, digits.length - 1 - i);
}
return res;
}
}

Code for finding pythagorean triplets

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;
}
}
}

Categories