VBA find the 2 closed numbers that a factors of my number

rpaulson

Well-known Member
Joined
Oct 4, 2007
Messages
1,377
Looking for some code that will return the closes 2 numbers that are factors of a given number.

given number 12: the 2 factor that are the closest to each other are 3 & 4 (not 2 & 6)

24 would return 6 & 4 (not 8 & 3 or 2 & 12)
64 would return 8 & 8 (not 16 & 4)
90 would be 9 & 10
37 would return 1 & 37
....

ex:
x= input(Type your number)
...code...

msgbox ("highest factors are " & F1 & " and " & F2)


Thanks for looking
Ross
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Code:
Function CloseFactors(n As Long) As String
  Dim i             As Long

  For i = Sqr(n) To 1 Step -1
    If n Mod i = 0 Then
      CloseFactors = i & ", " & n / i
      Exit For
    End If
  Next i
End Function

A​
B​
C​
1​
55​
5, 11B1: =CloseFactors(A1)
2​
56​
7, 8
3​
57​
3, 19
4​
58​
2, 29
5​
59​
1, 59
6​
60​
6, 10
7​
61​
1, 61
8​
62​
2, 31
9​
63​
7, 9
10​
64​
8, 8
 
Last edited:
Upvote 0
Give this function a try...
Code:
Function NearestFactors(Num As Long) As String
  Dim X As Long
  For X = Int(Sqr(Num)) To 1 Step -1
    If Num Mod X = 0 Then
      NearestFactors = X & " and " & Num / X
      Exit Function
    End If
  Next
End Function
 
Upvote 0
You could try this code - some data validation is built in:

Code:
Sub ClosestFactors()    
    Num = Application.InputBox("Enter a positive integer", "Enter number", , , , , , 1)
    If Num <> Int(Num) Or Num <= 0 Then GoTo BadInput
    num1 = Int(Sqr(Num))
    For i = num1 To 1 Step -1
    If Num Mod i = 0 Then
    MsgBox ("Closest factors are " & i & " and " & Num / i)
    Exit Sub
    End If
    Next
BadInput:
    MsgBox ("Invalid input"): Exit Sub
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,215,372
Messages
6,124,532
Members
449,169
Latest member
mm424

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top