▼页尾

# [Project Euler] Problem 4

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.

#include <iostream>using namespace std;int main(){    int palindrome;    int flag = 0;        for(int i=999; i>100; i--){        palindrome = 1000*i + i/100 + i%10*100 + i%100/10*10;                for(int j=999; j>100; j--){            if(palindrome%j==0 && palindrome/j <1000){                cout << palindrome << endl;                flag = 1;                break;            }        }                if(flag==1)             break;    }    return 0;}

100001 / 999 > 100

palindrome/j <1000 即可，而不需要 palindrome/j > 100对于999999，最开始999999/999 = 1001，已经大于1001了，所以对于998～100的数我们不需要最做除法了。所以简单改进后变为#include <iostream>using namespace std;int main(){    int palindrome;    int flag = 0;        for(int i=999; i>100; i--){        palindrome = 1000*i + i/100 + i%10*100 + i%100/10*10;                for(int j=999; j>100; j--){            if(palindrome/j > 999)                 break;            else if(palindrome%j==0){                    cout << palindrome << endl;                    flag = 1;                    break;                }        }                if(flag==1)             break;    }    return 0;}


posted @ 2011-02-20 22:31 xiatwhu 阅读(...) 评论(...) 编辑 收藏
▲页首