### FermatsFactor.py 
### https://en.wikipedia.org/wiki/Fermat%27s_factorization_method
###
### MIT License 
### Copyright (c) 2017 636F57@GitHub 
### See more detail at https://github.com/636F57/CryptoAttackers/blob/master/LICENSE 


from decimal import *
import time
import sys


bFileOutput = True

def fermatsFactorBasic(N):  
	NN = Decimal(N)
	A = NN.sqrt()    
	A = A.to_integral_value(rounding=ROUND_CEILING)
	b2 = A * A - NN
	
	tmp = b2.sqrt()
	while tmp != tmp.to_integral_value():
		A += 1                  # search upward to find A such that A = (p+q)/2
		b2 = A * A - NN
		tmp = b2.sqrt()
		
	p = A + tmp                 # tmp = abs((p-q)/2)
	q = A - tmp
	return int(p), int(q) 

if __name__ == "__main__":

	getcontext().prec = 4096

	N = Decimal(input("Enter N as base-10 integer:"))

	if N < 0 or N % Decimal(2) == 0:
		print("N must be a positive odd integer.")
		sys.exit()	
	
	t_start = time.time()
	
	p, q = fermatsFactorBasic(N)  

	t_taken = time.time()-t_start

	if bFileOutput:
		with open("factor_out.txt", "w") as f:
			strOut = "N = " + str(N) + "\n"
			f.write(strOut)
			print(strOut)
			strOut = "p = " + str(p) + "\n"
			f.write(strOut)
			print(strOut)  
			strOut = "q = " + str(q) + "\n"
			f.write(strOut)
			print(strOut)
			strOut = "calc time =" + str(t_taken // 60) + " min " + str(t_taken % 60) + " sec" + "\n"
			f.write(strOut)
			print(strOut) 
	else:
		print( "N =", N)
		print( "p =", p)
		print( "q =", q)
		print( "calc time =", t_taken // 60, " min", t_taken % 60, "sec")
		
	print("done")

@@ -428,16 +428,23 @@
  - NN%0A%09%0A
+%09try:%0A%09
 %09tmp = b
@@ -452,16 +452,17 @@
 .sqrt()%0A
+%09
 %09while t
@@ -492,16 +492,17 @@
 alue():%0A
+%09
 %09%09A += 1
@@ -567,16 +567,17 @@
 (p+q)/2%0A
+%09
 %09%09b2 = A
@@ -588,16 +588,17 @@
  - NN%0A%09%09
+%09
 tmp = b2
@@ -605,16 +605,85 @@
 .sqrt()%0A
+%09except KeyboardInterrupt:%0A%09%09print(%22Interrupted. A=%22,A)%0A%09%09sys.exit()%0A
 %09%09%0A%09p = 

add keyboardinterrupt