算法设计之Project Euler 04:Largest palindrome product

一、问题

Largest palindrome product

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.

二、问题描述

回文数(palindromic number)指的是不管从哪边读都是一样的数字,且能够被分解为两个数的乘积。

比如一对由两个数字组成的最大回文数(palindromic number)是9009,且9009=91×99.

那么找出一对由三个数字组成的最大回文数(palindromic number)。

答案是:906609

三、第一遍刷Project Euler

思路:回文数非常有特点,如果三个数字分别为abc,那么组成的回文数为abccba,据此可以写一个函数来生成所有的三个数字组成的回文数。同时,回文数能够分解为两个数的乘积。三个数字组成的6位数,最大可以分解为两个1000×1000以内的数,据此可以写一个分解回文数的函数。最后需要找到这个回文数,找到之后推出程序即可。

python版本的代码为:

# 生成回文数的函数
def pal_num(a, b, c):
    return a * 100001 + b * 10010 + c * 1100


# 分解回文数的函数
def can_be_divided(x):
    for i in range(999, 0, -1):
        for j in range(999, 0, -1):
            if (i*j)==x:
                print(x, " can be divided by ", i, " and ", j)
                return True
    return False


# 找最大的回文数
def main():
    for a in range(9, 0, -1):
        for b in range(9, -1, -1):
            for c in range(9, -1, -1):
                x = pal_num(a, b, c)
                if can_be_divided(x):
                    break


if __name__ == '__main__':
    main()


# 输出结果为:906609  can be divided by  993  and  913

C++版本的代码为:

#include<iostream>
#include<vector>

int pul_num(int a, int b, int c)
{
	return a * 100001 + b * 10010 + c * 1100;
}

bool can_be_divided(int x)
{
	for (int i = 999; i > 0; i--)
	{
		for (int j = 999; j > 0; j--)
		{
			if (i*j==x)
			{
				std::cout << x << " can be diveded by " << i << " and " << j << std::endl;
				return true;
			}
		}
	}
	return false;
}

void main()
{
	for (int a = 9; a > 0; a--)
	{
		for (int b = 9; b >= 0; b--)
		{
			for (int c = 9; c >= 0; c--)
			{
				int x = pul_num(a, b, c);
				if (can_be_divided(x))
				{
					goto breakloop;
				}
			}
		}
	}

	breakloop: system("pause");
}

猜你喜欢

转载自blog.csdn.net/z704630835/article/details/82689177