fermat factorization

This commit is contained in:
2025-10-17 10:35:14 +02:00
parent 0c6aa7fcce
commit 6392eeaadb

35
fermat-factorization.hs Normal file
View File

@@ -0,0 +1,35 @@
import Text.Read (readMaybe)
import System.Exit (exitSuccess)
main :: IO ()
main = do
n <- askNumber
let (d, root) = findIntegerSqrt n
q = (root - d)
p = (root + d)
putStrLn ("n = " ++ show n)
putStrLn ("Found d = " ++ show d ++ ", sqrt(n + d^2) = " ++ show root)
putStrLn ("q = " ++ show q ++ ", p = " ++ show p)
askNumber :: IO Int
askNumber = do
putStrLn "Enter an integer:"
input <- getLine
case readMaybe input :: Maybe Int of
Just n -> return n
Nothing -> do
putStrLn "Not a valid integer!"
exitSuccess
-- Find the smallest integer d >= 0 such that sqrt(n + d^2) is an integer
findIntegerSqrt :: Int -> (Int, Int)
findIntegerSqrt n = go 0
where
go d =
let val = n + d*d
root = floor (sqrt (fromIntegral val))
in if root * root == val
then (d, root)
else go (d + 1)