Convert vb.net code in python for educational purposes. No numeric value output

My day job is mostly encoded in vb.net, so I am very familiar with it. Performing my first few dozens of problems of project eulers, I used vb.net only to get problem styles hanging. Now I would like to use the project Euler to help me learn a new language and run a couple in python. But. I am trapped.

The following code will print the largest simple coefficient for 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 works fine. I think the equivalent in python is:

 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 in print. Am I missing the python nuance? Where could I do wrong? Thanks:)

+4
source share
1 answer

Previous solutions generate the wrong answer.

  • VB.net code works with integers, and your Python code works with floats, and this apparently doesn't work.
  • As mentioned earlier, the key phrase is (True / False).
  • You can use foo% bar == 0 without any problems.
  • You missed one level of indentation in the line "factor = 0".

This code gives 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 
+2
source

All Articles