Simple problem

Hi, I was thinking for a few days at a C++ problem and I couldn't solve it, I tried but I'm a begginer.
So n and k are two natural numbers with max. five numbers in them. (Example : 11111).
It will need to output the sum of N in K even numbers.
Examples:
For n = 18 and k = 3 the output will be 2+6+10=18
For n = 10 and k = 4 it will say "it's impossible)
English isn't my native language so please be kind.
Thank you!
Last edited on
What part did you get stuck on? This is basically just one for loop adding to a variable. For i from n to k, if i is even add i to sum.
Last edited on
If n is odd, then it is impossible. That you can test easily.

Why is n=10, k=4 impossible? No repeats and no 0 allowed?

18/2 = 9
1+2+3 = 6
9-6 = 3

2*1 = 2
2*2 = 4
2*(3+3) = 12
2+4+12 = 18
I don't get it. Maybe you could write in your native language, and use google translate?

Aceix.
I misread.

"It will need to output the sum of N in K even numbers."

n is the number, which has to be even for this to work, and k is how many even numbers you have to use as its sum.

That's why n=10, k=4 is impossible - There is no way with four natural even numbers you can add to 10 (2+4+6+8 is already too high)

I'll do some thinking about how to solve it.
Last edited on
Ok got it! So do you need tips on how to write a code for that?

Aceix.
Done it!Thanks guys.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream.h>
int main()
{
	int n,k,suma,i;
	cin >> n;
	cin >> k;
	if(n<(k*(k+1)) || n%2!=0)
	{
		cout << "No";
	}
	
	suma=0;
	for(i=1;i<=k;i++)
	{
		if(i<k)
		{
			cout << i*2 << "+";
			suma+=i*2;
		}
		else
		{
			cout << n-suma;
		}
	}
}
Ah, so there are multiple solutions to most problems - that simplifies the program a lot.

Fixed compile errors:
http://ideone.com/g6SKvb

You should note that <iostream.h> is deprecated, you are supposed to use <iostream> without the .h
Thank you L B, keskiverto and Aceix!
Topic archived. No new replies allowed.