How to calculate all the less than 500 additive prime numbers in VB.NET

1 Answer

0 votes
Imports System

' Additive primes: primes whose sum of digits is also prime

Module AdditivePrimes

    ' Check if a number is prime
    Function IsPrime(n As UInteger) As Boolean
        If n < 2UI Then Return False
        If n Mod 2UI = 0UI Then Return n = 2UI
        If n Mod 3UI = 0UI Then Return n = 3UI

        Dim i As UInteger = 5UI
        While i * i <= n
            If n Mod i = 0UI Then Return False
            i += 2UI
            If n Mod i = 0UI Then Return False
            i += 4UI
        End While

        Return True
    End Function

    ' Compute the sum of digits of a number
    Function SumDigits(n As UInteger) As UInteger
        Dim sum As UInteger = 0UI
        While n > 0UI
            sum += n Mod 10UI
            n \= 10UI
        End While
        Return sum
    End Function

    ' Check if a number is an additive prime
    Function IsAdditivePrime(n As UInteger) As Boolean
        Return IsPrime(n) AndAlso IsPrime(SumDigits(n))
    End Function

    Sub Main()
        Const TOP As UInteger = 500UI
        Dim count As Integer = 0

        For n As UInteger = 1UI To TOP - 1UI
            If IsAdditivePrime(n) Then
                Console.Write("{0,3}", n)
                count += 1
                If count Mod 10 = 0 Then
                    Console.WriteLine()
                Else
                    Console.Write(" ")
                End If
            End If
        Next

        Console.WriteLine()
        Console.WriteLine()
        Console.WriteLine("Total additive primes = " & count)
    End Sub

End Module

				

'run:
'
'  2   3   5   7  11  23  29  41  43  47
' 61  67  83  89 101 113 131 137 139 151
'157 173 179 191 193 197 199 223 227 229
'241 263 269 281 283 311 313 317 331 337
'353 359 373 379 397 401 409 421 443 449
'461 463 467 487
'
'Total additive primes = 54
'

 



answered May 4 by avibootz
...