0

(Btw we haven't used arrays yet. Im in my loop chapter)

I need to write a Java program that will output all pairs of positive integers, (a,b) such that a and b are greater than or equal to 0 and less than or equal to 1000 and the ratio (a^2 + b^2 + 1) / (a*b) is an integer.

My way to go about it is make a nested loop

for (a = 0; a <= 1000; a++)
    for (b = 0; b <= 1000; b++)
    {
        //answer = a^2 + b^2 + 1 / (a*b)
        //if (answer % 1 == 0)
        //    System.out.println("(" + a + ", " + b + ")") 
    }

would that work properly or am i looking at this problem all wrong

Bob
  • 59
  • 1
  • 2
  • 8
  • 1
    You should use `if( (a*a + b*b + 1) % (a*b) == 0 )` to see if a²+b²+1 is divisible by ab. Using `%` right away works on all numeric types. Your current approach only works on floating-point types (`float` and `double`), because of integer division. Dividing an `int` by an `int` would result in an `int`. – Lone nebula May 24 '13 at 04:34

3 Answers3

1

I think your approach is correct,

But one thing you make sure,

you are using the expression : answer = a^2 + b^2 + 1 / (a*b)

But you have mentioned in your question as (a^2 + b^2 + 1) / (a*b).

So make sure that you are using those parenthesis, otherwise operator precedence may cause you some problem

Like 1 / (a*b) will be solved after (a*b) is completed and you don't want it like that, right. So take care of operator precedence or use parenthesis.

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
0

Using nested loops would be an exhaustive search and is probably the most straight-forward approach to this problem. A couple of things to keep in mind:

  1. The ^ operator is actually an XOR operator. Use Math.pow(a, 2) or a * a if you are looking to sqaure a
  2. Beware of integer division
  3. You probably want to start your loops at 1 instead of 0
Community
  • 1
  • 1
DannyMo
  • 11,344
  • 4
  • 31
  • 37
  • i was summarizing thats why it was a comment and not code. I HAVE to use that formula I HAVE to start at 0 (greater than or EQUAL to) – Bob May 24 '13 at 04:06
  • Gotcha. I suggested not starting at 0 because you said _positive_ integers, and when diving by 0 (e.g. when a and b are both 0) your ratio will result in NaN or an exception (in the case of integer division) – DannyMo May 24 '13 at 04:13
0

I can change your expression to following:

  1. (a^2 + b^2 + 1+2ab-2ab) / (a*b)
  2. ((a+b)^2-2ab)/(a*b)
  3. (a+b)^2/ab -2

So equation is simple now you need to check that (a+b)^2/ab > 2. Ultimate check is that sum of 2 numbers should be divisible by their product.

Add a check for a=0 and b=0 as both are divisors.

Lokesh
  • 7,810
  • 6
  • 48
  • 78