【歐拉計劃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

(全文完)

發佈了98 篇原創文章 · 獲贊 12 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章