haskell中的主要分解

问题描述 投票:2回答:1

我正在编写一个程序,对于给定的整数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,实际上是将其对应的指数放进去,然后输出。我已经尝试过:

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部分到处都是丑陋的。事情是我不知道该使用什么,因为定义y时我也需要使用x,但这是集合理解的一部分。我尝试过更改它,或使用“ where”,但是它始终存在“ y”的问题,告诉我它不在范围之内。对此有什么优雅的解决方案?

list haskell list-comprehension primes
1个回答
3
投票

简单的答案是

y == potencia n x

应该阅读

let y = potencia n x

并且您不需要检查mod n (x^y) == 0-我认为根据potencia的定义,这将是正确的。

[您还有其他可以做的事情,但是它们很整洁。

© www.soinside.com 2019 - 2024. All rights reserved.