Project Euler 1-5
今天发现一个很好玩的网站:projecteuler.net/,都是我喜欢的数论题
处理数字,我最喜欢!
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
#include<stdio.h> int main() { int i,ans; ans = 0; for(i = 3;i < 1000;i++) if(i % 3 == 0 || i % 5 == 0) ans += i; printf("%d\n",ans); return 0; }
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
#include<stdio.h> int main() { long long n,t,tmp,ans; t = 1; n = 1; ans = 0; while(n <= 4000000) { tmp = n; n = n + t; t = tmp; if(n % 2 == 0) ans += n; } printf("%lld\n",ans); return 0; }
Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
#include<stdio.h> int main() { long long num = 600851475143ll; int i = 2; while (num > 1) { while(num % i == 0) num /= i; i++; } i--; printf("%d\n",i); return 0; }
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<stdio.h> int check(int n) { if(back(n) == n) return 1; return 0; } int back(int n) { int t; t = 0; while(n != 0) { t = t * 10 + n % 10; n /= 10; } return t; } int main() { int n,m,ans,max; max = -1; for(n = 100;n <= 999;n++) for(m = n;m <= 999;m++) { ans = m * n; if(check(ans) && ans > max) max = ans; } printf("%d\n",max); return 0; }
Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
#include<stdio.h> int main() { int ans; ans = 1 * 16 * 9 * 5 * 7 * 11 * 13 * 17 * 19; printf("%d\n",ans); return 0; }