简体   繁体   中英

How to find the largest palindrome made from the product of two 3-digit numbers in vb.net?

I am trying to solve a puzzle and the Problem statement is: Find the largest palindrome made from the product of two 3-digit numbers.

I'm new to this so please help!

Here's a basic outline that should get you going:

Dim max As Integer = 999 * 999
Dim min As Integer = 100 * 100
Dim result As Integer

While max > min AndAlso Not (IsPalindrome(max) AndAlso Not IsPrime(max)) Then
    max -= 1   
End While
result = max

And then the functions you need:

Public Function IsPalindrome(ByVal value As Integer) As Boolean
   Dim str1 As String = value.ToString()
   Dim chars() As Char = str1.ToCharArray()
   Array.Reverse(chars)
   Dim str2 As New String(chars)
   Return (str1 = str2)
End Function

Public Function IsPrime(ByVal value As Integer) As Boolean
    If value Mod 2 = 0 Then
        Return False
    End If
    For i = 3 To value / 2 + 1 Step 2
        If value Mod i = 0 Then
            Return False
        End If
    Next
    Return True
End Function

Here is C/C++ code for solving this problem, you'll need to do 2 things- 1) convert this into VB code and 2) implement the isPalindrome() function.

int highestPalindrome = 12321; // 111 * 111
for( int i = 111; i <= 999; i++) {
    for( int j = 111; j<= 999; j++) {
        int value = i*j;
        if( isPalindrome(value) )
            if( value > highestPalindrome )
                highestPalindrome = value;
    }
}

There are NUMEROUS solutions you can find on Stack Overflow for writing the isPalindrome() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM