2
首先,對於我的'noobness',第一次發佈感到抱歉。haskell中的素質factorizacion
我正在做一個程序,對於一個給定的整數n,返回一個整數對的列表,其中第一個元素是n的素因式分解的一個素數,第二個元素是對應的指數那素數。例如對於n = 50,它將輸出[(2,1),(5,2)],因爲50 =(2^1)*(5^2)。
所以無論如何,這是我的代碼:
--returns all numbers that divide x
divis :: Integer -> [Integer]
divis 1 = []
divis x = [n | n<-[2..(x-1)], mod x n == 0]
--checks if a number is prime
isprime :: Integer -> Bool
isprime 1 = False
isprime n = if divis n == [] then True else False
--list of prime numbers that divide x
facto :: Integer -> [Integer]
facto 1 = []
facto x = [n | n <- (divis x), isprime n == True]
--finds the biggest exponent of a number m that divides another number n
potencia :: Integer -> Integer -> Integer
potencia _ 0 = error "error"
potencia _ 1 = error "error"
potencia n m = (head [x | x <- [0..], not(mod n (m^x) == 0)]) - 1
下一步將是,對於一個數n,我可以把togheter一對在事實上每個數n及其對應的指數,並輸出那。 我曾嘗試與此:
factorizar :: Integer -> [(Integer, Integer)]
factorizar 0 = error "nope"
factorizar 1 = [(1,1)] --This isn't accurate but I'll change it later
factorizar n = [(x,y) | x<-(facto n), y == potencia n x, mod n (x^y) == 0] --THIS
我知道,在修真集合在y部分是醜陋的無處不在。事情是我不知道要使用什麼,因爲爲了定義我還需要使用x,但它是集合理解的一部分。我嘗試過改變它,或使用'where',但它總是有'y'的問題,告訴我它不在範圍之內。什麼可能是一個優雅的解決方案呢?
樣式註釋:不要寫'if divis n == [] then True else False',只需寫入'divis n == []'或者甚至是null(divis n)'。同樣,不要寫'isprime n == True',只需寫'isprime n'。 – chi