Hi
Was working on a problem:
Write a program (GUI or command line) that accepts input, performs calculations and returns output to the user. Provide source code (with project files if applicable) and if we are unable to compile the code for some reason we will request binaries (please put these in a RAR file or a password protected ZIP or our email system will bounce the email).
Please provide basic error checking on input and adequate comments. Correctness is very important, efficiency is a bonus. Source code clarity is highly valued. Fancy formatting or a GUI is not required. This is a chance to showcase your skills, so write the program in a way that will best display your talent.
Input: K, N (where 0 < N < ∞, 0 < K < ∞, and K <= N)
Output: Number of possible equations of K numbers whose sum is N
Example Input:
N=10
K=3
Example Output:
1 + 1 + 8 = 10
1 + 2 + 7 = 10
1 + 3 + 6 = 10
1 + 4 + 5 = 10
2 + 2 + 6 = 10
2 + 3 + 5 = 10
2 + 4 + 4 = 10
3 + 3 + 4 = 10
Total unique equations = 8
For reference, N=100, K=3 should have a result of 833 unique sets and print out 833 equations.
I got the partial solution:
Code:
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
/* main takes 2 arguments K,N such that where 0 < N < inf, 0 < K < inf, and K <= N.*/
/*K and N are integers.*/
int main(int argc, char** argv)
{
char number1[20], number2[20];//size check
int numk,n;
int total=0;
printf("usage: Input k:<number1>\n\t Input n:<number2>\n");
printf("Input k:");
scanf("%s",number1);
numk= (int)strtol (number1, NULL, 10 );
printf("\nInput n: ");
scanf("%s",number2);
n = (int)strtol ( number2, NULL, 10 );
if(n>0 )
{
if(numk>0 && numk<=n)
{
for(int i=1;i<=(n-2);i++)
{
for (int j=i; j<=(n-1-i);j++)
{
int k= n-i-j;
if(k>=j){
total++;
printf("%d + %d+ %d= %d\n",i,j,k,n);
}
}
}
printf("Number of equations are:%d\n",total);
}
else
printf("Error: n>0,k>0 and k<= n.\n");//try agin loop
}
/*
** Ensure that argv[argc] is indeed NULL by printing
** a message if (argv[argc] == NULL) evaluates to true.
*/
if ( argv[argc] == NULL )
puts ( "This is the end" );
return EXIT_SUCCESS;
}
This is for one k value only and want to generalise it.how do we get a recussive solution so the k is auto mated.Also the code I wrote is in c style but compiles with g++.I wanted it to be more c++ style.I am not used/experienced with c++ much.
Any help is appreciated.
Thanks
shweta