VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Determine Prime and return Factors

by Thomas D. Tomlins (2 Submissions)
Category: Math/Dates
Compatability: Visual Basic 3.0
Difficulty: Advanced
Date Added: Wed 3rd February 2021
Rating: (2 Votes)

Determine if a number is Prime if it is not prime return Factors of the number

Inputs
Long number
Code Returns
If not prime returns factors otherwise returns that the number is Prime
Side Effects
None Known

Rate Determine Prime and return Factors

Option Explicit
'Add two textboxes 1- txtFactors(Returns Factors) and 1- Text1(Input number
'Two commandbuttons 1-cmdPrimeand 1-cmdPrime2
'One Label 1-Label2
Private Sub cmdPrime_Click()
  Dim I As Long, J As Long, Num As Long
  Num = Val(Text1.Text)
  
  If Num <= 3 Then
    Label2.Caption = "Entry is Prime"
    Exit Sub
  End If
  If Num Mod 2 = 0 Then
    Label2.Caption = "Entry is Not Prime"
    Exit Sub
  End If
    I = Int(Sqr(Num))  ' Should be Sqrt(Num)
    For J = 3 To I Step 2
     If Num Mod J = 0 Then
        Label2.Caption = "Entry is Not Prime"
        Exit Sub
     End If
    Next J
   
  Label2.Caption = "Entry is Prime"
    
End Sub
Private Sub cmdPrime2_Click()
  Dim Factors As New Collection
  Dim I As Long, J As Long, K As Long, L As Long, Num As Long
  Num = Val(Text1.Text)
    I = Int(Sqr(Num))  ' Should be Sqrt(Num)
    For J = 2 To I
     If Num Mod J = 0 Then
        L = Factors.Count \ 2
        K = Num \ J
        If Factors.Count > 0 Then
        Factors.Add J, , , L
        If (K <> J) Then Factors.Add K, , , L + 1
        Else
        Factors.Add J
        If (K <> J) Then Factors.Add K
        End If
        
     End If
    Next J
    If Factors.Count = 0 Then
     txtFactors.Text = Text1.Text & " is prime."
    Else
     txtFactors.Text = Text1.Text & " is not prime." & vbCrLf
     txtFactors.Text = txtFactors.Text & "It is divisible by "
    For I = 1 To Factors.Count
    txtFactors.Text = txtFactors.Text & Factors.Item(I) & " ,"
    Next I
    End If
End Sub

Download this snippet    Add to My Saved Code

Determine Prime and return Factors Comments

No comments have been posted about Determine Prime and return Factors. Why not be the first to post a comment about Determine Prime and return Factors.

Post your comment

Subject:
Message:
0/1000 characters