Find the largest palindrome made from the product of two 3-digit numbers

前端 未结 17 985
天涯浪人
天涯浪人 2021-02-02 04:27
package testing.project;

public class PalindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i+         


        
相关标签:
17条回答
  • 2021-02-02 05:01

    What about : in python

    >>> for i in range((999*999),(100*100), -1):
    ...     if str(i) == str(i)[::-1]:
    ...         print i
    ...         break
    ...
    997799
    >>>
    
    0 讨论(0)
  • 2021-02-02 05:05
     package ex;
    
        public class Main {
    
            public static void main(String[] args) {
                int i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, flag = 0;
    
                for (i = 999; i >= 100; i--) {
                    for (j = i; j >= 100; j--) {
                        k = i * j;
    
                        // System.out.println(k);
                        m = 0;
                        n = k;
    
                        while (n > 0) {
                            l = n % 10;
                            m = m * 10 + l;
                            n = n / 10;
                        }
    
                        if (m == k) {
                            System.out.println("pal " + k + " of " + i + " and" + j);
                            flag = 1;
                            break;
                        }
                    }
    
                    if (flag == 1) {
                        // System.out.println(k);
                        break;
                    }
                }
            }
        }   
    
    0 讨论(0)
  • 2021-02-02 05:05

    A slightly different approach that can easily calculate the largest palindromic number made from the product of up to two 6-digit numbers.

    The first part is to create a generator of palindrome numbers. So there is no need to check if a number is palindromic, the second part is a simple loop.

    #include <memory>
    #include <iostream>
    #include <cmath>
    
    using namespace std;
    template <int N>
    class PalindromeGenerator {
        unique_ptr <int []> m_data;
        bool m_hasnext;
    public :
        PalindromeGenerator():m_data(new int[N])
        {
            for(auto i=0;i<N;i++)
            m_data[i]=9;
            m_hasnext=true;
       }
      bool hasNext() const {return m_hasnext;}
    
    long long int getnext()
    {
        long long int v=0;
        long long int b=1;
        for(int i=0;i<N;i++){
            v+=m_data[i]*b;
            b*=10;
        }
        for(int i=N-1;i>=0;i--){
            v+=m_data[i]*b;
            b*=10;
        }
    
        auto i=N-1;
        while (i>=0)
        {
            if(m_data[i]>=1) {
                m_data[i]--;
                return v;
            }
            else 
            {
                m_data[i]=9;
               i--; 
            }
        }
    
        m_hasnext=false;
        return v;
    }
    
    
    };
    
    template<int N>
    void findmaxPalindrome()
    {
        PalindromeGenerator<N> gen;
        decltype(gen.getnext()) minv=static_cast<decltype(gen.getnext())> (pow(10,N-1));
        decltype(gen.getnext()) maxv=static_cast<decltype(gen.getnext())> (pow(10,N)-1);
        decltype(gen.getnext()) start=11*(maxv/11);
        while(gen.hasNext())
        {
            auto v=gen.getnext();
            for (decltype(gen.getnext())  i=start;i>minv;i-=11)
            {
                if (v%i==0)
                {
                    auto r=v/i;
                    if (r>minv && r<maxv ){
                        cout<<"done:"<<v<<" "<<i<< "," <<r <<endl;
                        return ;
                    }
                }
    
          }
        }
    
    return ;
    }
    int main(int argc, char* argv[])
    {
        findmaxPalindrome<6>();
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-02 05:05

    This is code in C, a little bit long, but gets the job done.:)

    #include <stdio.h>
    #include <stdlib.h>
    /*
    A palindromic number reads the same both ways. The largest palindrome made from the                                 product of two
    2-digit numbers is 9009 = 91  99.
    
    Find the largest palindrome made from the product of two 3-digit numbers.*/
    
    int palndr(int b)
    {
    int *x,*y,i=0,j=0,br=0;
    int n;
    n=b;
    while(b!=0)
    {
       br++;
       b/=10;
    }
    x=(int *)malloc(br*sizeof(int));
    y=(int *)malloc(br*sizeof(int));
    
    int br1=br;
    
    while(n!=0)
    {
        x[i++]=y[--br]=n%10;
        n/=10;
    }
    
    int ind = 1;
    for(i=0;i<br1;i++)
    if(x[i]!=y[i])
    ind=0;
    free(x);
    free(y);
    return ind;
    }
    
    int main()
    {
       int i,cek,cekmax=1;
       int j;
       for(i=100;i<=999;i++)
       {
           for(j=i;j<=999;j++)
            {
            cek=i*j;
    
           if(palndr(cek))
            {
                if(pp>cekmax)
                cekmax=cek;
            }
            }
       }
    
       printf("The largest palindrome is: %d\n\a",cekmax);
    }
    
    0 讨论(0)
  • 2021-02-02 05:10

    We can translate the task into the language of mathematics.

    For a short start, we use characters as digits:

    abc * xyz = n 
    
    abc is  a 3-digit number, and we deconstruct it as 100*a+10*b+c
    xyz is  a 3-digit number, and we deconstruct it as 100*x+10*y+z
    

    Now we have two mathematical expressions, and can define a,b,c,x,y,z as € of {0..9}.
    It is more precise to define a and x as of element from {1..9}, not {0..9}, because 097 isn't really a 3-digit number, is it?

    Ok.

    If we want to produce a big number, we should try to reach a 9......-Number, and since it shall be palindromic, it has to be of the pattern 9....9. If the last digit is a 9, then from

    (100*a + 10*b + c) * (100*x + 10*y + z) 
    

    follows that z*c has to lead to a number, ending in digit 9 - all other calculations don't infect the last digit.

    So c and z have to be from (1,3,7,9) because (1*9=9, 9*1=9, 3*3=9, 7*7=49).

    Now some code (Scala):

    val n = (0 to 9)
    val m = n.tail // 1 to 9
    val niners = Seq (1, 3, 7, 9)
    val highs = for (a <- m;
      b <- n;
      c <- niners; 
      x <- m;
      y <- n;
      z <- niners) yield ((100*a + 10*b + c) * (100*x + 10*y + z))
    

    Then I would sort them by size, and starting with the biggest one, test them for being palindromic. So I would omit to test small numbers for being palindromic, because that might not be so cheap.

    For aesthetic reasons, I wouldn't take a (toString.reverse == toString) approach, but a recursive divide and modulo solution, but on todays machines, it doesn't make much difference, does it?

    // Make a list of digits from a number: 
    def digitize (z: Int, nums : List[Int] = Nil) : List[Int] =
      if (z == 0) nums else digitize (z/10, z%10 :: nums)
    
    /* for 342243, test 3...==...3 and then 4224. 
       Fails early for 123329 */
    def palindromic (nums : List[Int]) : Boolean = nums match {
      case Nil           => true 
      case x :: Nil      => true 
      case x :: y :: Nil => x == y 
      case x :: xs       => x == xs.last && palindromic (xs.init) }
    
    def palindrom (z: Int) = palindromic (digitize (z))
    

    For serious performance considerations, I would test it against a toString/reverse/equals approach. Maybe it is worse. It shall fail early, but division and modulo aren't known to be the fastest operations, and I use them to make a List from the Int. It would work for BigInt or Long with few redeclarations, and works nice with Java; could be implemented in Java but look different there.

    Okay, putting the things together:

    highs.filter (_ > 900000) .sortWith (_ > _) find (palindrom) 
    res45: Option[Int] = Some(906609)
    

    There where 835 numbers left > 900000, and it returns pretty fast, but I guess even more brute forcing isn't much slower.

    Maybe there is a much more clever way to construct the highest palindrom, instead of searching for it.

    One problem is: I didn't knew before, that there is a solution > 900000.


    A very different approach would be, to produce big palindromes, and deconstruct their factors.

    0 讨论(0)
  • 2021-02-02 05:12

    What I would do:

    1. Start at 999, working my way backwards to 998, 997, etc
    2. Create the palindrome for my current number.
    3. Determine the prime factorization of this number (not all that expensive if you have a pre-generated list of primes.
    4. Work through this prime factorization list to determine if I can use a combination of the factors to make 2 3 digit numbers.

    Some code:

    int[] primes = new int[] {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
    73,79,83,89,97,101,103,107,109,113,,127,131,137,139,149,151,157,163,167,173,
    179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,
    283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,
    419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,
    547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,
    661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,
    811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,
    947,953,967,971,977,983,991,997};
    
    for(int i = 999; i >= 100; i--) {
    
        String palstr = String.valueOf(i) + (new StringBuilder().append(i).reverse());
        int pal = Integer.parseInt(pal);
        int[] factors = new int[20]; // cannot have more than 20 factors
        int remainder = pal;
        int facpos = 0;
        primeloop:
        for(int p = 0; p < primes.length; i++) {
            while(remainder % p == 0) {
                factors[facpos++] = p;
                remainder /= p;
                if(remainder < p) break primeloop;
            }
        }   
        // now to do the combinations here 
    }
    
    0 讨论(0)
提交回复
热议问题