Re: A Simple C Code to Discuss



In article <1130644594.620414.151060@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
ethanmys <ethanori@xxxxxxxxx> wrote:
>hello everyone. hours ago i found a topic about solving the problem:
>find out 2 int between certain rang, say 1---100, both the 2 int's sum
>and minus should be a int's square. i write this piece of code and i
>want you to give some advice. can the code run quicker? i think there
>must exist many quicker ones.

Let me translate. You are stating:
Problem 1:
Find all integers x and y between 1 and N such that
x+y and x-y are squares.

However your program does not solve this. It solves the following
problem instead:
Problem 2:
Find all integers x and y such that x+y and x-y are squares
and x+y is at most N.

Aside: Your table of squares is missing 7^2 = 49:

> int tb[][6]={{1,9,25,81,121,169},\
> {4,16,36,64,100,144,}};

To solve the problems stated above, it's best to do a little
math before writing a program. You are looking for x and
y such that:

x + y = a^2, x - y = b^2.

By solving this system of two equations in the two unknowns
x, and y we get:

x = (a^2 + b^2)/2, y = (a^2 - b^2)/2.

We observe that a and b have to be both even or both odd,
otherwise the fractions shown above will not yield integers.

In view of this, we can print the numbers you are looking
for as follows:

int i, j, I, J, N;

for (i=1; I=i*i, i<=N; i++)
for (j=i+2; J=j*j, j<=N; j+=2)
printf("(%d, %d)\n", (J+I)/2, (J-I)/2);

This solves Problem 1. To solve Problem 2, change the
stopping criteria i<=N and j<=N to I<=N and J<=N.

--
Rouben Rostamian
.



Relevant Pages

  • Rectangles
    ... the children were asked to do that consisted of drawing a rectangle ... squares it passes through (any square passed through conts as 1 even ... However I've not got far in solving it. ...
    (sci.math)
  • Re: factoring using geomerty?
    ... Draw two squares, one of side x and another with side y. ... unshading area is clearly a square with sides (x-y). ... You get a long thin rectangle. ... Paul Leyland, pleyland@ | Thought I'd something more to say. ...
    (sci.crypt)