Int -> t0 -> t0
덕분에 예상과 일치 할 수 없습니다,하지만 실제로 소수를 찾을 수 없습니다. 나는 함수 이름 주위 백틱 표기법 종류의 중위 "연산자"로 그것을 설정하는 것입니다
floor $ sqrt $ fromIntegral number
에
fromInteger (`sqrt` number)
을 변경했다, 그래서 당신은
mod x y
을 할 수
또는
x `mod` y
그러나
`mod` x y
다음으로, Int
의 (Int
및 Integer
다른 종류)에서 작동 하나입니다, 대신 fromIntegral
의 fromInteger
를 사용하고 있었다. 마지막으로 number
이 Int
이므로 checkDiv
의 두 번째 가드에서 floor
을 제거했습니다.
isPrime :: Int -> Bool
isPrime number
| (number == 1) || (number == 2) = True
| even number = False
| otherwise = checkDiv number (floor $ sqrt $ fromIntegral number)
checkDiv :: Int -> Int -> Bool
checkDiv number divisor
| number == 2 = True
| (number `mod` divisor) == 0 = False
| otherwise = checkDiv number $ divisor - 1
그래서 코드가 어떻게 진행되고 있는지 살펴 봅시다. 나는 (4
이 floor $ sqrt $ fromIntegral 17
입니다) checkDiv 17 4
을 계산한다면, 그것은
checkDiv 17 4
| 17 == 2 No
| 17 `mod` 4 == 0 No
| otherwise = checkDiv 17 (4 - 1) = checkDiv 17 3
checkDiv 17 3
| 17 == 2 No
| 17 `mod` 3 == 0 No
| otherwise = checkDiv 17 (3 - 1) = checkDiv 17 2
checkDiv 17 2
| 17 == 2 No
| 17 `mod` 2 == 0 No
| otherwise = checkDiv 17 (2 - 1) = checkDiv 17 1
checkDiv 17 1
| 17 == 2 No
| 17 `mod` 1 == 0 Yes = False
그러나 17
가 소수 수행 할 것입니다! 당신의 알고리즘이 잘못된 것을 어디에서 보았습니까?
이 문제로 해결하려는 것은 무엇입니까? – bheklilr
왜 'sqrt'를 백틱에 넣었습니까? 그냥'(sqrt number)'를 사용하십시오. –
number가 소수 일 경우 isPrime 숫자가 true이고, 그렇지 않은 경우 false이지만이 알고리즘을 사용하고자합니다. – msietrterc