【问题标题】:Prime factorizacion in haskellHaskell中的素数分解
【发布时间】:2014-07-11 19:24:24
【问题描述】:

我正在编写一个程序,对于给定的整数 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,我可以将每个数字放在一对中,实际上是它对应的指数,然后输出它。 我试过这个:

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'总是有问题,告诉我它不在范围之内。对此有什么优雅的解决方案?

【问题讨论】:

  • 风格说明:不要写if divis n == [] then True else False,只写divis n == []甚至null (divis n)。同样,不要写isprime n == True,只写isprime n

标签: list haskell list-comprehension primes


【解决方案1】:

简单的答案是

y == potencia n x

真的应该读

let y = potencia n x

而且你不需要检查mod n (x^y) == 0 - 我认为根据potencia 的定义它会是真的。

您还可以做一些不同的事情,但它们都是整理出来的。

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 2019-09-30
    • 2011-08-30
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    相关资源
    最近更新 更多