Java – find the largest palindrome made by the product of two 3-digit numbers

package testing.project;
package testing.project;

public class palindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i++)
        {
            for(int j = i;j <=999;j++)
            {
                int value1 = i * j;
                StringBuilder sb1 = new StringBuilder(""+value1);
                String sb2 = ""+value1;
                sb1.reverse();
                if(sb2.equals(sb1.toString()) && value<value1) {
                    value = value1;

                }

            }
        }

        System.out.println(value);
    }
}

This is the code I wrote in Java... What other effective methods are there Can we optimize this code more?

Solution

We assume that the largest such palindrome will have six digits instead of five, because 143 * 777 = 111111 is a palindrome

As mentioned elsewhere, the 6 - bit Radix - 10 palindrome abccba is a multiple of 11 This is correct because * 100001 b * 010010 c * 001100 equals 11 * a * 9091 11 * b * 910 11 * c * 100 Therefore, in our inner loop, if M is not a multiple of 11, we can reduce N by 11 steps

We are trying to find the largest palindrome below a million, which is the product of two 3-digit numbers To find a large result, we first try a large divisor:

>Let's start with 999 and move down 1, then 1; > Run n down from 999 by 1 (if 11 divided by m, or 9% of the time) or from 990 divided by 11 (if 11 does not divide by m, or 91% of the time)

We trace the largest palindrome found in variable Q so far Suppose q = R · s, where r < = s. We usually have m < R < = s. We require m · n > Q or n > = q / m. due to the discovery of large palindromes, the range of n is more limited for two reasons: Q becomes larger and M becomes smaller The internal loop of the additional program is executed only 506 times, compared with ~ 810000 times of the simple program used

#include <stdlib.h>
#include <stdio.h>
int main(void) {
  enum { A=100000,B=10000,C=1000,c=100,b=10,a=1,T=10 };
  int m,n,p,q=111111,r=143,s=777;
  int nDel,nLo,nHi,inner=0,n11=(999/11)*11;

  for (m=999; m>99; --m) {
    nHi = n11;  nDel = 11;
    if (m%11==0) {
      nHi = 999;  nDel = 1;
    }
    nLo = q/m-1;
    if (nLo < m) nLo = m-1;

    for (n=nHi; n>nLo; n -= nDel) {
      ++inner;
      // Check if p = product is a palindrome
      p = m * n;
      if (p%T==p/A && (p/B)%T==(p/b)%T && (p/C)%T==(p/c)%T) {
        q=p; r=m; s=n;
        printf ("%d at %d * %d\n",q,r,s);
        break;      // We're done with this value of m
      }
    }
  }
  printf ("Final result:  %d at %d * %d   inner=%d\n",s,inner);
  return 0;
}

Note that the program is in C, but the same technology will work in Java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>