I created a Python script to find two whole numbers that, when multiplied together, will equal the target number, or factors. My script works by dividing the target number by a regularly increasing integer, and checking to see if the quotient is a whole number (integer).

Here's the script:

#!/usr/bin/python

cnum = 21
cntnu = 1
currint = 1


#Begin Loop

while cntnu == 1:
	currint = currint + 1
	oput = cnum/currint
	if type(oput) == type(1):
		cntnu = 0
		print "Factorization Found."
		print oput
		print "x"
		print currint
	else:
		print "Factorization failed. Trying next factorization..."
#End Loop

However, when I run this I get this output:

Factorization Found.
10
x
2

Obviously, not 21.

What am I doing wrong?

Thanks in advance!

In Python versions before Python3 if you use '/' for division and divide two integers, the result will always be an integer.

In Python versions before Python3 if you use '/' for division and divide two integers, the result will always be an integer.

I'm running Python 2.5.2. That's my problem.

Edit:
After changing the top line to

#!/usr/bin/python3

I get the error in terminal:

print "Factorization Found."
                               ^
SyntaxError: invalid syntax

thats because in python30 you need to use

print("this is an example")

as print is a function in python30

Okay, my code now looks like this:

#!/usr/bin/python3

cnum = 21
cntnu = 1
currint = 2


#Begin Loop

while cntnu == 1:
	
	oput = cnum/currint
	if type(oput) == type(1):
		cntnu = 0
		print('Factorization Found.')
		print(oput)
		print('x')
		print(currint)
	else:
		print(currint," Factorization failed. Trying next factorization...")
		currint = currint + 1
#End Loop

Now the script continues on, heedless of the if statement, stating that 3 and 7 don't work. Is my code incompatible with 3.0, by chance?

Now it doesn't work because '/' gives a result of type float. You got to use another criterion like the modulus operator.

I tried this (my brain is off today):

#Begin Loop

while cntnu == 1:
	
	oput = cnum/currint
	remaintest = oput % 1

	if remaintest == 0:
		cntnu = 0
		print('Factorization Found.')
		print(oput)
		print('x')
		print(currint)
	else:
		print(currint," Factorization failed. Trying next factorization...")
		currint = currint + 1
#End Loop

And it worked!

Thanks!

You can also use divmod.

cnum = 21
cntnu = 1
currint = 1
  
#Begin Loop
 
while cntnu == 1:
	currint = currint + 1
	whole, remain = divmod(cnum, currint)
	if 0 == remain:
		cntnu = 0
		print "Factorization Found."
		print whole, remain 
		print currint, cnum
	else:
		print currint, "Factorization failed. Trying next factorization..."
This article has been dead for over six months. Start a new discussion instead.