Scriptorium

us fr nl




VBA : Project Euler: Project Euler - Problem #3   nl


Options: Save as PDF | Save attached file | Toggle line numbers

Details:

Type: sub
Added By: Rembo
Short Description:
None
Notes:
The problem description is included with the code.
Added: Mar 13 2009 at 1:56 PM
Related URLs


Usage:

Run the routine, the answer is printed in the debugging screen.


Code:

Formatted | Unformatted
  1. Sub Euler_0003()
  2. 'The prime factors of 13195 are 5, 7, 13 and 29.
  3. '
  4. 'What is the largest prime factor of the number 600851475143 ?
  5.  
  6.  
  7. Dim i As Long, i2 As Long
  8. Dim arrNums() As Long
  9. Dim sNum As String
  10. Dim cPrimes As Collection
  11. 'Store enough prime numbers in a collection
  12. i2 = Int(Sqr(Len("600851475143")) + 1)
  13. For i = 1 To i2
  14. sNum = sNum & "9"
  15. Next i
  16. Set cPrimes = New Collection
  17. For i = 1 To CLng(sNum) Step 2
  18. cPrimes.Add i, CStr(i)
  19. Next i
  20.  
  21. For i = cPrimes.Count To 1 Step -1
  22. If cPrimes(i) / 3 = Int(cPrimes(i) / 3) Then
  23. cPrimes.Remove i
  24. End If
  25. Next i
  26.  
  27. For i = cPrimes.Count To 1 Step -1
  28. If cPrimes(i) / 5 = Int(cPrimes(i) / 5) Then
  29. cPrimes.Remove i
  30. End If
  31. Next i
  32. For i = cPrimes.Count To 1 Step -1
  33. If cPrimes(i) / 7 = Int(cPrimes(i) / 7) Then
  34. cPrimes.Remove i
  35. End If
  36. Next i
  37.  
  38. 'Remove squares of primes
  39. For i = cPrimes.Count To 1 Step -1
  40. If Sqr(cPrimes(i)) = Int(Sqr(cPrimes(i))) Then
  41. cPrimes.Remove i
  42. End If
  43. Next i
  44.  
  45. For i = cPrimes.Count To 1 Step -1
  46. If 600851475143# / cPrimes(i) = Int(600851475143# / cPrimes(i)) Then
  47. Debug.Print cPrimes(i)
  48. Exit Sub
  49. End If
  50. Next i
  51. End Sub



User comments :

Add a new comment   Back to Top
Atom Feed
Contact | About This Application | Scriptorium Website