2017-01-07 4 views
-3

誰かが自分のコードを修正できるかどうか不思議でした。これはプロジェクトオイラーの質問3(数字600851475143の最大の素因数は何ですか?)です。今のところ、私はプログラムに固執しています100ですべての素因数を見つけることができますが、私の頭の中で0で割り切ってエラーメッセージが表示されていますが、コードはうまくいくようですが、そうではありません。絶対に必要でない限り、私はwhileループを維持したいと思います。ありがとう。プロジェクトオイラーナンバー3 - Python

def isPrime(A): 
    x = 2 
    while x < A: 
      if A % x == 0: 
        return False 
      x += 1 
    return A 

def isInt(x): 
    if x == int(x): 
      return True 
    return False 

A = int(input("Number? ")) 
counter = 2 

while counter <= A: 
    if isInt(A/isPrime(counter)) == True: 
      print(counter) 
    counter += 1 

print ("Done") 
+2

'isPrime()'が 'return False'という行を実行している場合、' if isInt(A/False) 'というコードを実行しています。 sense(そして 'False'はおそらく0に強制され、' ifInt(A/0) 'になります) – Aurora0001

+1

まあ...' isPrime'は 'false'を返すことができます。どの数値がそれに関連付けられているのか推測したいですか? – usr2564301

+0

商が整数かどうかを調べるのに悪い方法!ちょうど 'A%B == 0'のためにテストします –

答えて

0

重要な問題がisPrime()が時々ブール値を返すことであるようで、他の時間は入力(整数)を返します。一度に多くのことをする関数を避けるべきです。isPrime()という関数はと入力しなければなりません。は入力が素数であるかどうかを示します(常にブール値を返します)。

def isPrime(n): # n is a common variable name to use for "some number" 
    x = 2 
    while x < n: 
    if n % x == 0: 
     return False 
    x += 1 # this isn't an ideal way to detect primes, can you think of any improvements? 
    return True 

def isInt(n): # use consistent variables - you used A above and x here, which is confusing 
    return n == int(n) # you can just return the boolean result directly 

input = int(input("Number? ")) # use meaningful variable names when possible 
counter = 2 

while counter <= input: 
    # I *think* this is what you were trying to do: 
    # if counter is prime and input/counter is an integer. 
    # If not you may need to play with this conditional a bit 
    # also no need to say ' == True' here 
    if isPrime(counter) and isInt(input/counter): 
    print(counter) 
    counter += 1 

print ("Done") 

これは実行する必要がありますが、それはまだそれができるほど効率的ではありません(それが動作するかどうか、私はあなたに残して!):他のいくつかの提案がインライン化。 Project Eulerの問題が深刻になるにつれ、効率と最適化に細心の注意を払う必要があります。私はあなたが、さらにこの掘り下げるてみましょう、しかし、ここであなたが始めるために、2つのヒントですよ:

1ずつ増加
  • たびに無駄である - あなたは何かが2で割り切れない知っていれば、あなたもそれが4で割り切れないことを知っています、8、16、などですが、あなたのコードはこれらのチェックを行います。
  • 一般に、素数を見つけることは高価であり、非常に反復的な操作です。次の素数を見つけるときに素数を見つけるために行われた作業はすべて再利用できますか?