Problem1:3或5的倍数
在小于10的自然数中,3或5的倍数有3、5、6和9,这些数之和是23。
求小于1000的自然数中所有3或5的倍数之和。
#include<stdio.h>
#include<iostream>
using namespace std;
int a;
int main()
{
for (int i = 0; i < 1000; i++)
if (i % 3 == 0 || i % 5 == 0)
a += i;
cout << a;
}
Problem2:偶斐波那契数
斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列的前10项为:
1,2,3,5,8,13,21,34,55,89,…
考虑该斐波那契数列中不超过四百万的项,求其中为偶数的项之和。
#include<stdio.h>
#include<iostream>//cout用到的头文件
using namespace std;
int main()
{
int m = 0, n = 1, s = m + n, sum = 0;
while (s < 400000)
{
m = n;
n = s;
s = m + n;
if (s % 2 == 0)
{
sum += s;
}
}
cout << sum;
}
Problem3:最大质因数
13195的质因数包括5、7、13和29。
600851475143的最大质因数是多少?
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int m = 13195;
int i = 2;
while (m > 2)
{
if (m % i == 0)
{
cout << i << " ";
m = m / i;//如果没有这个,会无限的输出5
}
else
{
i += 1;
}
}
}<