views:

150

answers:

1

My day job is mainly coding in vb.net, so I am very familiar with it. While doing my first few dozen project euler problems, I used vb.net just to get the hang of the problem styles. Now I'd like to use project euler to help me learn a new language and have been running a couple in python. However. I've hit a snag.

The following code will print the largest prime factor of a given number:

Protected Function isPrime(ByVal n As Long) As Boolean
    If n = 2 Then
        Return True
    End If
    If n Mod 2 = 0 Then
        Return False
    End If

    Dim maxFactor As Long = Math.Sqrt(n)
    Dim i As Integer = 3
    While i <= maxFactor
        If n Mod i = 0 Then
            Return False
        End If
        i = i + 2
    End While
    Return True
End Function

Protected Sub LargestPrimeFactor(ByVal n As Long)
    Dim factor As Long = Math.Sqrt(n) ''#largest factor of n will be sqrt(n)
    While factor > 2
        If (n Mod factor) = 0 Then
            If isPrime(factor) Then
                Me.lblAnswer.Text = factor
                factor = 0
            End If
        End If
        factor = factor - 1
    End While
End Sub

This vb.net code runs perfectly. The equivalent in python, I believe to be:

from math import sqrt

    def IsPrime(n):
        if n==2: return true
        if not n % 2: return false

        maxFactor = sqrt(n)
        i = 3
        while i <= maxFactor:
            if not n % i: return false
            i += 2
        return true

    n = 600851475143
    factor = sqrt(n)
    while factor > 2:
        if not n % factor:
            if IsPrime(factor):
                print factor
            factor = 0
        factor -= 1

However, the factor never ends up printing. Am I missing a nuance of python? Where might I have gone wrong? Thanks :)

+1  A: 

Previous solutions generate wrong answer.

  1. VB.net code operates on integers, and your Python code operates on floats, and this apparently fails somewhere.
  2. As mentioned before, keyword capitalization (True/False).
  3. You can use foo % bar == 0 with no problem.
  4. You missed one level of indentation in "factor = 0" line.

This code produces the correct answer, 6857:

from math import sqrt

def IsPrime(n):
    if n==2: return True
    if n % 2 == 0: return False

    maxFactor = long(sqrt(n))
    i = 3
    while i <= maxFactor:
        if n % i == 0: return False
        i += 2
    return True

n = 600851475143
factor = long(sqrt(n))
while factor > 2:
    if n % factor == 0:
        if IsPrime(factor):
            print factor
            factor = 0
    factor -= 1
PiotrLegnica
Mucho thanks! My downfalls were the false != False issue and the sqrt resolving to a different type than I expected.
Chris