【欧拉计划4】Largest palindrome product

欢迎访问我的新博客:http://www.milkcu.com/blog/

原文地址:http://www.milkcu.com/blog/archives/1371624960.html

原创:【欧拉计划4】Largest palindrome product

摘要:找出两个3位数乘积得到的最大回文数

作者:MilkCu

题目描述

Problem 4  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.

我的解答

第一次做的答案是580085,提交后提示错误,原来程序逻辑错误,得出的并不是最大的。增加max判断后,程序就对了。

# include <stdio.h>

int isPal(int n);
int reverse(int n);

int main(void)
{
	int p;
	int max = 0;
	for(int i = 999; i >= 100; i--) {
		for(int j = 999; j >= i; j--) {
			p = i * j;
			if(isPal(p)) {
				if(p > max) {
					max = p;
				} else {
					break;
				}
			}
		}
	}
	printf("%d\n", max);
}

int isPal(int n)
{
	if(n == reverse(n)) {
		return 1;
	} else {
		return 0;
	}
}

int reverse(int n)
{
	int r = 0;
	do {
		r = r * 10 + n % 10;
	} while(n /= 10);
	return r;
}

不断改进

看了projecteuler.net给的pdf,内容大致如下:

  1. 变量j的循环从i开始;
  2. 变量i和j的循环由大到小;
  3. 回文数必被11整除;

从第三点得到的启发还是很大的。

我们可以从下面的关系式得出这个结论:

P = 100000x + 10000y + 1000z + 100z + 10y + x
P = 100001x + 10010y + 1100z
P = 11 * (9091x + 910y + 100z)

改进后的代码如下:

# include <stdio.h>

int isPal(int n);
int reverse(int n);

int main(void)
{
	int p;
	int max = 0;
	int i, j, step;
	for(i = 999; i >= 100; i--) {
		if(i % 11 == 0) {
			j = 999;
			step = 1;
		} else {
			j = 990;
			step = 11;
		}
		for(; j >= i; j--) {
			p = i * j;
			if(isPal(p)) {
				if(p > max) {
					max = p;
				} else {
					break;
				}
			}
		}
	}
	printf("%d\n", max);
}

int isPal(int n)
{
	if(n == reverse(n)) {
		return 1;
	} else {
		return 0;
	}
}

int reverse(int n)
{
	int r = 0;
	do {
		r = r * 10 + n % 10;
	} while(n /= 10);
	return r;
}

最后答案

906609

(全文完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值