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

前端 未结 17 976
天涯浪人
天涯浪人 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:16

    I believe there is a simpler approach: Examine palindromes descending from the largest product of two three digit numbers, selecting the first palindrome with two three digit factors.

    Here is the Ruby code:

    require './palindrome_range'
    require './prime'
    
    def get_3_digit_factors(n)
      prime_factors = Prime.factors(n)
    
      rf = [prime_factors.pop]
      rf << prime_factors.shift while rf.inject(:*) < 100 || prime_factors.inject(:*) > 999
    
      lf = prime_factors.inject(:*)
      rf = rf.inject(:*)
    
      lf < 100 || lf > 999 || rf < 100 || rf > 999 ? [] : [lf, rf]
    end
    
    def has_3_digit_factors(n)
      return !get_3_digit_factors(n).empty?
    end
    
    pr = PalindromeRange.new(0, 999 * 999)
    n = pr.downto.find {|n| has_3_digit_factors(n)}
    puts "Found #{n} - Factors #{get_3_digit_factors(n).inspect}, #{Prime.factors(n).inspect}"
    

    prime.rb:

    class Prime
    
      class<

    palindrome_range.rb:

    class PalindromeRange
    
      FIXNUM_MAX = (2**(0.size * 8 -2) -1)
    
      def initialize(min = 0, max = FIXNUM_MAX)
        @min = min
        @max = max
      end
    
      def downto
        return enum_for(:downto) unless block_given?
    
        n = @max
        while n >= @min
          yield n if is_palindrome(n)
          n -= 1
        end
        nil
      end
    
      def each
        return upto
      end
    
      def upto
        return enum_for(:downto) unless block_given?
    
        n = @min
        while n <= @max
          yield n if is_palindrome(n)
          n += 1
        end
        nil
      end
    
      private
    
      def is_palindrome(n)
        s = n.to_s
        i = 0
        j = s.length - 1
        while i <= j
          break if s[i] != s[j]
          i += 1
          j -= 1
        end
        i > j
      end
    
    end
    

提交回复
热议问题