欧拉计划–C++编程突破2
Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
13195的质因数是5、7、13和29。 数600851475143的最大质因数是多少?
解题思路:与其思考最大质因数是多少,不如去思考怎么将非质因数剔除,首先这个数挺大,但是LL能放下,那就直接用LL类型解决,但是还是要压缩数据范围,首先,不管怎样,i * i 一定小于num,这是循环的范围(这样数据不会有大于i的因子),然后从小到大剔除因子,最后应该除不到1,剩下的一个数不能再除,就会是最大质因子。
#include<stdio.h>
#define N 600851475143LL
int main() {
long long i = 2, ans = 0, num = N;
while(i * i <= num) {
if(num % i == 0) ans = i;
while(num % i == 0) {
num /= i;
i += 1;
}
}
if(num != 1) ans = num;
printf("%lld/n",ans)
return 0;
}
验证answer = 6857
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.
回文数字的两种读法相同。 由两个2位数字的乘积制成的最大回文是9009=91×99。 找出由两个3位数的乘积制成的最大回文。
解题思路:本题主要考点是回文数的判断,判断回文数思路其实比较简单,把一个数字的每一位都考虑成一个数字,然后每次取出最后一位,然后加到新数字的第一位,最后与原数字进行比较。具体做法是每次对10取余,取出最后一位,加在新数字的最高位上,最后两个数字进行比较即可。除此之外再控制范围和选取数字即可。
#include <stdio.h>
int is_val(int x, int base) {
int tmp = x, sum = 0;
while(x) {
sum = sum * base + x % base;
x /= base;
}
return sum == tmp;
}
int main() {
int ans = 0;
for(int a = 100; a < 1000; a++) {
for(int b = ans / a + 1; b <= a; b++) {
if(is_val(a * b, 10) && ans < a * b) ans = a * b;
}
}
printf("%d\n", ans);
return 0;
}
验证answer = 906609