알고리즘 공부 Part3 : 소수 구하기

in #kr-study6 years ago (edited)

예제는 파이썬으로 작성하였습니다.

알고리즘 공부 Part3 : 소수 구하기

소수의 정의

  • 1과 자기자신 외에 나누어 떨어지는 정수가 없는 양의 정수

예를 들어 0 이상의 2,3,5,7,11,13 같은 수를 의미합니다.

특정 숫자(N)가 소수인지 판별하는 프로그램을 개발한다고 할때

2부터 N -1까지 정수로 나눠 떨어지는 수가 있는지 없는지 확인 하여 소수인지를 판별하게 됩니다.

정수로 나누어 떨어지면 소수가 아니고 나누어 떨어지지 않으면 소수입니다.

소수 구하기 코드 작성

코드를 작성해 봅시다.

소수를 입력 받아 입력받은 숫자가 소수인지 판별하는 코드를 작성해 봅시다. 코드는 아래 와 같습니다.

def isPrime(input) :
    for i in range(2, input -1) :
        result = input % i
        if result == 0:
            return False
    return True

if __name__ == '__main__':
    input = input()
    prime = isPrime(input)
    if prime == True :
        print("Prime")
    else :
        print("Not Prime")

%연산자를 이용하여 반복문을 이용하여 2부터 N-1까지 정수로 나눈후 나머지가 있는지 없는지를 비교합니다.
N-1까지 나누는 동안 모든 수로 나눠지지 않으면 소수입니다.

소수인지 판별하는 코드를 작성해 보았습니다. 하지만 이 코드도 개선할 포인트가 있습니다.

소수를 구하는 방법을 바꾸는 것이 아닌 소수를 구하는 i의 범위를 줄이는 것입니다.

소수 구하기 코드 개선

위코드로는 10이라는 숫자가 소수인지 판별하기 위해서 2부터 9까지 나눠봐야합니다. 만약 제곱근까지만 나누면 어떻게 될까요?

10은 2x5, 5x2 두가지 조합만 가집니다. 이를 통해 제곱근까지만 나눈다면 실행횟수를 줄일수 있습니다.

import math

def isPrime(input) :
    sqrn = int(math.sqrt(input))
    for i in range(2, sqrn) :
        result = input % i
        if result == 0:
            return False
    return True

if __name__ == '__main__':
    input = input()
    prime = isPrime(input)
    if prime == True :
        print("Prime")
    else :
        print("Not Prime")

Python에서 제곱근을 구하는 함수를 사용하기 위해서는 math를 임포트 한후 sqrt함수를 이용하면 됩니다.
제곱근까지만 나눠본후 결과를 출력해줍니다.

오늘 포스팅은 여기까지 입니다.

다음은 링크드 리스트를 알아 봅시다.

감사합니다.

Sort:  

짱짱맨 호출로 왔습니다.

감사합니다

pairplay 가 kr-dev 컨텐츠를 응원합니다! :)

5월 다시 파이팅해요!
호출에 감사드립니다!

Would you want to get the Real Time STEEM Price with iOS App? Try our new app!

Steem Current

https://itunes.apple.com/us/app/steemcurrent-real-time-price/id1356919022?ls=1&mt=8

STEEM Current provides latest price of STEEM real-time. It’s the best app for get real-time STEEM price.

It also can get:

  • Price in BTC
  • Hour Change
  • Day Change
  • Week Change
  • 24 Hour Volume
  • Market Cap
  • Market Cap Rank
  • Available Support
  • Total Support
  • Your Account Value

행복하세요! 감사합니다.

Congratulations @evasioner! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Congratulations @evasioner! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Do not miss the last post from @steemitboard:

Carnival Challenge - Collect badge and win 5 STEEM
Vote for @Steemitboard as a witness and get one more award and increased upvotes!

Congratulations @evasioner! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!