Project Euler:Product-sum numbers (problem 88) C++

时间:2023-03-09 20:47:29
Project Euler:Product-sum numbers (problem 88) C++

A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak.

For example, 6 = 1 + 2 + 3 = 1 × 2 × 3.

For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.

k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6

Hence for 2≤k≤6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum.

In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is {4, 6, 8, 12, 15, 16}, the sum is 61.

What is the sum of all the minimal product-sum numbers for 2≤k≤12000?

求积和数的一道题目,大多都是递归。

继续推导可以发现,f(k)的取值在[k,2k]之间。

可以推出,k=num-因子和+(num-因子和)*1;

那好了,就是写个<set>去重,写出递归函数就可以。

#include<iostream>
#include<set>
using namespace std;
set<int> Q;
set<int>::iterator it;
bool re(int x,int y,int z);
int getn(int n)
{
for(int k=n+1;k<=2*n;k++) //k的取值 k---2k
{
if(re(k,k,n)) //num, sum, digit
return k;
}
}
bool re(int x,int y,int z)
{
//cout<<x<<" "<<y<<" "<<z<<endl;
if(y<z)
return 0;
if(x==1)
return y==z;
if(z==1)
return x==y;
for(int i=2;i<=x;i++)
{
if(x%i==0)
{
// cout<<" i="<<i<<endl;
if(re(x/i,y-i,z-1))
return 1;
} }
return 0;
}
int main()
{
int n;
long long s=0;
for(int i=2;i<=12000;i++)
{
n=getn(i);
Q.insert(n); //此处可以直接判断 insert()的返回值,求和。
}
for(it=Q.begin();it!=Q.end();it++)
{
s+=*it;
}
cout<<s<<endl;
} //execution time : 21.385 s