这个Prime测试功能有什么问题?

时间:2018-01-20 01:19:41

标签: haskell primes

我几乎到处都看,我找不到为什么以下代码不起作用:

var barOptions_stacked = {
    title: {
      display:true,
      position:'top',
      text:'Hours Spent to Create Website',
    },
    tooltips: {
        enabled: true
    },
    hover :{
        animationDuration:400
    },
    scales: {
        xAxes: [{
            ticks: {
                beginAtZero:true,
            },
            scaleLabel:{
                display:true,
                labelString:'Hours Worked',
            },
            gridLines: {
            },
            stacked: true
        }],
        yAxes: [{
            gridLines: {
                display:false,
                color: "#fff",
                zeroLineColor: "#fff",
                zeroLineWidth: 0
            },
            stacked: true
        }]
    },
    legend:{
        display:false
    },
};
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    responsive:true,
    type: 'horizontalBar',
    data: {
        labels: ["Custom Built", "Site Builder"],

        datasets: [{
            label:'Hours for Required Content',
            data: [12, 2],
            backgroundColor: 'rgba(54, 162, 235, 0.8)',
            borderColor: 'rgba(54, 162, 235, 1)',
        },{
            label:'Hours for Added Features',
            data: [8.5, 0],
            backgroundColor: 'rgba(255, 70, 100, .8)',
            borderColor: 'rgba(255, 70, 100, 1)',
        },]
    },

    options: barOptions_stacked,
});

我得到两个错误,这些错误真的很长,所以我会把我认为重要的一点:

isPrime :: Int -> Bool
isPrime 1 = False
isPrime n = divTest n (floor (sqrt n))
    where
    divTest :: Int -> Int -> Bool
    divTest n test
        | test == 1         = True
        | mod n test == 0   = False
        | otherwise         = divTest n (test-1)

No instance for (RealFrac Int) arising from a use of ‘floor’

是的,我知道这可能不是有效的。我在学。

3 个答案:

答案 0 :(得分:3)

sqrt需要浮动 - 尝试

isPrime n = divTest n (floor (sqrt (fromIntegral  n)))

答案 1 :(得分:3)

由于sqrt的类型为:Floating a => a -> a,因此需要传递浮点数而不是整数。您可以将fromIntegral应用于n来执行此操作,如另一个答案中所示。

另一种可以解决这个问题的方法是将其分解为两个函数。

第一个函数可以找到最多n的所有因子:

factors :: Integer -> [Integer]
factors n = filter divides_n [1..n]
    where divides_n m = n `mod` m == 0

其工作原理如下:

*Main> factors 15
[1,3,5,15]

如果factors仅包含1n,我们可以使用它来检查数字是否为素数:

isPrime :: Integer -> Bool
isPrime n = factors n == [1,n]

按预期工作:

*Main> isPrime 2
True
*Main> isPrime 3
True
*Main> isPrime 4
False
*Main> isPrime 5
True
*Main> isPrime 15
False

这种方法的好处是你不必做任何棘手的事情来测试一个数字是否为素数。

答案 2 :(得分:3)

计算平方根的另一种方法是计算商的余数,并在商小于除数时停止。

-- Work our way up from 3, testing odd divisors only.
divTest :: Int -> Int -> Bool
divTest n test | r == 0 = False
               | q < test = True -- test > sqrt n, and we've tested all the smaller divisors
               | otherwise = divTest n (test + 2)

isPrime :: Int -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n = n `mod` 2 /= 0 && divTest n 3
相关问题