[Tutor] Creatively solving math problems -----help
Jeff Shannon
jeff at ccvcorp.com
Tue Sep 9 18:58:30 EDT 2003
Conrad Koziol wrote:
> hey i was trying to solve a math problem creativily and i wrote this
> script. Can anyone tell me why it doesn't work and how to fix it.
>
>
> for x in range(20000):
> if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4) and \
> x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 == int(x/7-1):
>
> print x
> else:
> pass
>
>
> The question is what whole numbers can be divided by 2-6 and have a
> remainder of 1 but divided by 7 and have no remainder. I already have
> the answer;
> 301 and then you add 420 each time. The problem is the program gives me
> every number between 1 and 19999.
The problem here is because you're using integer math. In integer
math, any fractional parts are dropped, which means that (for example)
3/2 == 1 -- not quite the effect that you want. You can fix this by
forcing floating point math. Just use x/2.0, x/3.0, etc.
Alternatively, if you're using Python 2.2, you can add "from
__future__ import division" (IIRC), and that will prevent the
truncation of fractional values to integers. (In Python 2.3, this
"true division" should be standard.)
> Also i was wondering how many line
> breaks can you use? I believe it gives me 1-19999 because im using ==
> but if i use only 1 = it gives me a syntax error. I believe this has
> something to do with the int(). Also int() returns it rounded down, is
> there any subsitute so it rounds to the nearest whole number.
No, it has nothing to do with int(). Python uses two equal signs, 'x
== y', to indicate equality ("test whether x equals y"). A single
equal sign, 'x = y', indicates assignment ("set x to be equal to y").
> Another way i though i could solve this was by a script that looks like
> this:
>
> for x in range(2000):
>
> if x/2 = int(x/2):
> continue
> else:
> ??????????
>
> the script would continue like this all the way to 7. The problem is i
> dont know a command that if if proves true skips that iteration and goes
> on to the next one.Any help??
The statement that does that is 'continue' -- you should be able to
use exactly what you've got there (with the assignment corrected to an
equality test, that is). Except that the 'else' is redundant -- if
the if statement is true, you'll never reach that point.
for x in range(2000):
if x/2.0 == int(x/2.0):
continue
if x/3.0 == int(x/3.0):
continue
[...]
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list