2013-10-11 3 views
2

하스켈의 여러 타입에 문제가 있습니다. 어떻게 해결할 수 있습니까?하스켈에서 타입과 관련된 문제

은 실제의 형태와 유형 Integer 내가 컴파일 코드를 얻기 위해 수정을 알아 냈어요

isPrime :: Int -> Bool 
isPrime number 
    | (number == 1) || (number == 2) = True 
    | even number = False 
    | otherwise = checkDiv number (fromInteger (`sqrt` number)) 

checkDiv :: Int -> Int -> Bool 
checkDiv number divisor 
    | number == 2 = True 
    | (floor number `mod` divisor) == 0 = False 
    | otherwise = checkDiv number $ divisor - 1 
+1

이 문제로 해결하려는 것은 무엇입니까? – bheklilr

+1

왜 'sqrt'를 백틱에 넣었습니까? 그냥'(sqrt number)'를 사용하십시오. –

+0

number가 소수 일 경우 isPrime 숫자가 true이고, 그렇지 않은 경우 false이지만이 알고리즘을 사용하고자합니다. – msietrterc

답변

7

Int -> t0 -> t0

덕분에 예상과 일치 할 수 없습니다,하지만 실제로 소수를 찾을 수 없습니다. 나는 함수 이름 주위 백틱 표기법 종류의 중위 "연산자"로 그것을 설정하는 것입니다

floor $ sqrt $ fromIntegral number 

fromInteger (`sqrt` number) 

을 변경했다, 그래서 당신은

mod x y 
을 할 수

또는

x `mod` y 

그러나

`mod` x y 

다음으로, Int의 (IntInteger 다른 종류)에서 작동 하나입니다, 대신 fromIntegralfromInteger를 사용하고 있었다. 마지막으로 numberInt이므로 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 

그래서 코드가 어떻게 진행되고 있는지 살펴 봅시다. 나는 (4floor $ 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가 소수 수행 할 것입니다! 당신의 알고리즘이 잘못된 것을 어디에서 보았습니까?

+0

고마워요! number == 2 대신 divisor가되어야합니다. – msietrterc

+0

올바른 것으로 알고리즘이 완성됩니다 (1을 소수로 간주하지만 큰 문제는 아닙니다). 다음 질문은 어떻게하면 더 빨리 달릴 수 있을까요? 인자 인지를보기 위해 2와'sqrt number '사이의 단일 숫자를 검사하고 있지만, 모든 짝수를 이미 걸러냅니다. 이상한 약수 만 체크하도록 프로그램을 수정할 수있는 간단한 방법이 있습니까? – bheklilr