Reputation: 475
I have an equation.
a4 + b4 = c4 + d4
The variables a, b, c and d can take any value from 0 to 1000. Write a program that would print all possible pairs of a, b and c, d that satisfy the above equation.
I tried to do it using Java.
One of the approaches I attempted was to build a map containing the key value pairs : <0,04>, <1,14>, <2,24>....<1000,10004>. After the map is built, I am looking to iterate through the values list and see if the sum of two elements in the list match the sum of two other elements in the list. I am stuck at this point.
public static void getMatchingPairs()
{
long a;
long b;
long c;
long d;
Map<Integer,Long> map = new HashMap<Integer, Long>();
for(int i = 0; i < 1001; i++)
{
long res = Double.valueOf(Math.pow(i, 4)).longValue();
map.put(i,res);
}
List<Long> lst = (List<Long>) map.values();
}
Upvotes: 0
Views: 951
Reputation: 533660
In addition to Andres' comments, using an LongStream is a much more natural solution.
Lets assume that a^4 + b^4 = b^4 + a^4 is not an interesting solution so instead what you want to find is when a <= b and c and d != a or b
Map<Long, List<long[]>> sums = LongStream.range(0, 1001)
.boxed()
.flatMap(a -> LongStream.range(a, 1001)
.boxed()
.map(b -> new long[]{a, b, a * a * a * a + b * b * b * b}))
.collect(Collectors.groupingBy(triple -> triple[2]));
sums.entrySet().stream()
.filter(e -> e.getValue().size() > 1)
.forEach(e -> System.out.println(
e.getValue().stream()
.map(t -> "(" + t[0] + "," + t[1] + ")")
.collect(Collectors.joining(", "))));
I have included the code here for you interest as you wouldn't be expect to write this for your homework yet.
Upvotes: 1
Reputation: 159135
Don't use double
math to calculate power of 4. Just multiply 3 times, i.e. calculate a*a*a*a + b*b*b*b
.
Then create a Map
of the result to a List
of the pairs used to calculate the result: Map<Long, List<int[]>>
where the int[]
is an array of two values, i.e. a "pair".
As an example, the pair (1,2)
results in value 17
, so does reverse pair (2,1)
. Since those are the only pairs with that result, your maps would include 17 = [(1,2), (2,1)]
.
Not sure what "print all possible pairs of a, b and c, d" means. Simple answer is just those 2 pairs (for result 17
).
More complex answer is that you need to print each combination of pairs, since each pair can be an (a,b)
pair or a (c,d)
pair, so you create all combination of pairs: (1,2),(1,2)
, (1,2),(2,1)
, (2,1),(1,2)
, and (2,1),(2,1)
.
That all seems very redundant, because for each (a,b)
pair where a != b
, there will be 4 combinations, so perhaps you only need to print results of a pair (not combination of pairs), and only when a <= b
, since a > b
is redundant.
Anyway, you need to print from all the value lists in the map for the full answer.
Upvotes: 2