-
VBA Mac coding Question
Trying to write code to show prime numbers 3-1000, then show the sum of the digits of each of those prime numbers, and ultimately just show the prime numbers whose sum is prime. Example the number is 11 to show 1+1=2, 2 would also be shown because it is also a prime number. I have the code working for prime numbers, however cannot get it to sum the digits or show the summed primes. Please help!
-
Have you tried this?
Code:
=SUMPRODUCT(--MID(A1,ROW(INDIRECT("1:" & LEN(A1))),1))
-
I see this was posted a few months ago. Are you still working on the problem? If so, you mention the sum of digits of 11 is 2 and 2 is prime. Are you summing all the digits of all the primes or only the sum of the digits that result in a prime sum? Are you doing this all in VBA or are you displaying all primes <1000 on a spreadsheet?
-
Okay after a little homework...
This code will print Prime Numbers from 3 to 1000 in column A
Code:
Sub FindPrimesToColumnA()
Dim i As Long
Dim j As Long
Dim IsPrime As Boolean
Dim RowNum As Long
RowNum = 1 ' Start writing primes from cell A1
Cells(RowNum, 1).Value = 2 '2 is the first prime
RowNum = RowNum + 1
For i = 3 To 1000 Step 2
IsPrime = True
For j = 3 To Sqr(i) Step 2
If i Mod j = 0 Then
IsPrime = False
Exit For
End If
Next j
If IsPrime Then
Cells(RowNum, 1).Value = i ' Write the prime number to column A
RowNum = RowNum + 1
End If
Next i
End Sub
This next set of codes should produce the sum of umbers to make each Prime.
Code:
Sub PrimeSums()
Dim i As Long, j As Long, k As Long
Dim IsPrime As Boolean
Dim RowNum As Long
RowNum = 1
Cells(RowNum, 1).Value = 2 '2 is the first prime
RowNum = RowNum + 1
For i = 3 To 1000 Step 2
IsPrime = True
For j = 3 To Sqr(i) Step 2
If i Mod j = 0 Then
IsPrime = False
Exit For
End If
Next j
If IsPrime Then
Cells(RowNum, 1).Value = i 'Write prime number
Cells(RowNum, 2).Value = FindSumCombinations(i) 'Write sum combinations
RowNum = RowNum + 1
End If
Next i
End Sub
Function FindSumCombinations(target As Long) As String
Dim a As Long, b As Long
Dim result As String
result = ""
For a = 2 To target - 2 'Start from 2
For b = a To target - a 'Start from a to avoid duplicates
If a + b = target Then
If result <> "" Then
result = result & "; " 'Separate combinations with semicolon
End If
result = result & a & "+" & b
End If
Next b
Next a
FindSumCombinations = result
End Function