C++ Console Challenge

nbk

Newbie
Joined
Aug 20, 2004
Messages
135
Reaction score
1
After spending hours on this issue(well, about an hour), I finally got my program to work right <:] .

Anyways, there are no limits as to how you make it.

What happens - the user inputs two numbers(n and x).

number * n + number * x = the third number inputted. This can be a workaround to solving it on paper.

For example: the user inputs 2 and 3. He then inputs a number that he wants (number * n + number * x) to equal.

If you need a better explanation(as from looking at it... it is sort of lame :()

I will post my solution once another working solution has been posted.
 
Could you give a better explanation?

From what I get, the user enters 3 numbers : x, y and n, producing:

z*x + z*y = n

Where you're trying to find z? But, that seems kinda too simple to me...
 
Yeah, that is what is what meant(although there is a different variable for each number(which can, of course, be the same)).

(Note - this was done in around 50-60 lines of code. The syntax is easily beginner's, and the thinking process would be around intermediate(on a beginner's scale))
 
this is psuedo code but i really don't know why this is so hard. just combine like terms using the distributive property

if z*x + z*y = n

z = n / (x+y)
 
There is 5 variables used, not 4.

..

z * x + n * i = a
 
a*b + c*d = n

Assume that a*b and c*d both equal n/2 (n/2 + n/2 = n)...

a = (n/2)/b
c = (n/2)/d

Code:
#include <iostream>

using namespace std;

int main(int argc, char**argv)
{
	if (argc < 4)
		return 1;
	
	int b = atoi(argv[1]);
	int d = atoi(argv[2]);
	int n = atoi(argv[3]);

	float n_2 = n/(float)2;
	
	float a = n_2/b;
	float c = n_2/d;

	cout << a << "*" << b << " + " << c << "*" << d << " = " << n << endl;

	return 0;
}
Please excuse any Bad code, It's been a while since I've played with C++.
 
Might post a solution in C# later. Only being halfway through 8th grade Geometry doesn't help either. I'm trying to get into 3D programming and I haven't even learned vector math yet...
 
henry, haven't tried that. However, using ints only adds to the challenge(which is what was expected; sorry for not stating that - whole numbers only!)

to you, N3ur0: how old are you?
 
num * n + num * x = res

very pseudo code:

input variables x,y,res
num = res / (x+y)
output num


this is a very simple algebra problem. do i win a prize? :D
 
Obsidian - I can give you an award for not looking through the whole thread. As I had said before, there are 5 variables, and no floats - that adds to the challenge.

to henry - exactly what I wanted, except with whole numbers.

Code:
#include <iostream>

using namespace std;

void findNumbers(int &, int &, int &, int &, int &, int &);
int whileLoop( int &timesFirst, int &timesSecond, int &resultWanted, int &firstNumber, int &secondNumber, int &maxTimesSecond );

int main()
{
    cout << "Enter first two numbers: ";
    int firstNumber, secondNumber, resultWanted, timesFirst, timesSecond, maxTimesSecond;
    cin >> firstNumber;
    cin >> secondNumber;
    
    cout << "\n\nEnter number to achieve: ";
    cin >> resultWanted;
    
    findNumbers( timesFirst, timesSecond, resultWanted, firstNumber, secondNumber, maxTimesSecond );
    whileLoop( timesFirst, timesSecond, resultWanted, firstNumber, secondNumber, maxTimesSecond );
    system("PAUSE");
}    

void findNumbers( int &timesFirst, int &timesSecond, int &resultWanted, int &firstNumber, int &secondNumber, int &maxTimesSecond )
{
    int countingResultWanted = resultWanted;
    while(countingResultWanted % firstNumber != 0)
    {
        countingResultWanted--;
    }
    timesFirst = countingResultWanted;

    
    countingResultWanted = resultWanted;
    
    while(countingResultWanted % secondNumber != 0)
    {
        countingResultWanted--;
    }
    timesSecond = countingResultWanted;
    maxTimesSecond = countingResultWanted / secondNumber + 1;
        
}



int whileLoop( int &timesFirst, int &timesSecond, int &resultWanted, int &firstNumber, int &secondNumber, int &maxTimesSecond )
{
    cout << timesSecond << " = timesSecond;\n\n";
    cout << timesFirst << " = timesFirst\n\n";
    cout << maxTimesSecond << " = maxTimesSecond\n\n";
    while( timesFirst * firstNumber + timesSecond * secondNumber != resultWanted )
    {
        if(timesSecond != 0)
        {
            timesSecond--;
        }
        cout << maxTimesSecond << " = maxTimesSecond\n\n";  
        cout << timesSecond << " = timesSecond \n\n";
        cout << timesFirst << " = timesFirst \n\n";
        if(timesSecond == 0)
        {
            cout << "Now in if()... timesSecond = " << timesSecond << " and maxTimesSecond = " << maxTimesSecond << " and timesFirst = " << timesFirst << "\n\n";
            timesSecond = maxTimesSecond;
            timesFirst--;
        }
    }
    cout << "\n\nNow NOTNOTNOTNOT in if()... timesSecond = " << timesSecond << " and maxTimesSecond = " << maxTimesSecond << " and timesFirst = " << timesFirst << " and timesSecond = " << timesSecond << "\n\n";
}

That is what was expected. It takes a fairly large amount of time to do, but it works. It's quite messy, though...

(back to you, N3ur0 - I am 13 myself, and something such as the pulse modification wouldn't be that hard - no reason not to believe you.)
 
@nbk
13, almost 14. And yes, I really did write PulseMod. I still don't see how this little math problem involves 5 variables. Actually, I think you've just inspired me to write an equation-solver in a language with POSIX-compatible regex functions...

I tested 2 of the solutions before nbk's, they were both wrong. Sorry henrym, but 1 * 2 + (2/3) does not equal 4.
 
N3ur0, mine came out to be 1*2 + 2/3(3).

You sure that isn't what you got?
 
I dunno, I had to build it with GCC since Micro$hit's compiler was spitting out errors left and right. But it is very basic syntax/functions/classes, so I don't see why GCC (gcc -lstdcx, actually) would screw it up.

EDIT: Nevermind, rebuilt with cl.exe after discovering the problem and it works fine. As it turns out M$ rewrote the iostream classes to use exception handling, so it will spit out a bunch of warnings (which after a while turn into errors) if you don't use the /EHsc switch. Never knew that before, since I don't write many console programs. :E
 
Are you allowed 0 and negative answers for p or q ?
 
Okay. I make no promises on this code, and its in C# because thats a lot nicer :)

Code:
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace math_mod
{
    class ProgramClass
    {
        static void Main(string[] args)
        {
            //formula xp + yq = z find possible values of p and q given x,y,z

            //Get Values
            Console.WriteLine("Solve equation x*p + y*q = z");
            Console.WriteLine("Enter x");
            int x = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter y");
            int y = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter z");
            int z = int.Parse(Console.ReadLine());

            int p, q; //The Final values;

            /*
            rearranging equation gives
            p + qy/x = z/x;
            all we need to do is find a point when the remiander of qy/x = remainder of z/x
            so when
            qy MOD x = z MOD x
            */

            double find = z % x;    //z MOD x
            int i = 0;              //Counter Variable to find q
            double j = -1;           //Holds value of qy/x for this iteration
            while ((j != find))
            {
                i++;        //Increase I at start, as we started from 0.

                if (i > 10000)  //Woah lets not get into an infinite loop if its unsolvable.
                {
                    Console.WriteLine("No Match");
                    Console.ReadLine();
                    return;
                }
                j = (i * y) % x;    //Create a new j value
            
            }
            //Success
            q = i;              //i is q
            p = (z - y*q) / x;  //find p
            Console.WriteLine(p + "*" + x + " + " + q + "*" + y + " = " + z); //print
            Console.ReadLine();
            return;
        }
    }
}

The Code is commented so read that. Some Credit to my friend christian for showing me a faster way of getting the remainders (and not having to worry about rounding them). Only problem with this is if u put some stupid combination in and it doesnt find the answer, doesnt check to make sure it is possible.
 
And I've already modified it.

basically if find (the remainder) is a multiple of j then the answer is a multiple of i, so change to increment by i can make it faster in some instances.

Code:
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace math_mod
{
    class ProgramClass
    {
        static void Main(string[] args)
        {
            //formula xp + yq = z find possible values of p and q given x,y,z

            //Get Values
            Console.WriteLine("Solve equation x*p + y*q = z");
            Console.WriteLine("Enter x");
            int x = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter y");
            int y = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter z");
            int z = int.Parse(Console.ReadLine());

            int p, q; //The Final values;

            /*
            rearranging equation gives
            p + qy/x = z/x;
            all we need to do is find a point when the remiander of qy/x = remainder of z/x
            so when
            qy MOD x = z MOD x
            */

            double find = z % x;    //z MOD x, what we want to find.
            int i = 0;              //Counter Variable to find q
            int increment = 1;    //How much to increment by.
            double j = -1;           //Holds value of qy/x for this iteration
            while ((j != find))
            {
                if (((find % j) == 0) && (i > 1)) //if remainder to find is a multiple of j, answer is a multiple of current i.
                {
                    //Answer is a multiple of current value!
                    increment = i;
                }

                i += increment;        //Increase I at start, as we started from 0.

                
                if (i > 10000)  //Woah lets not get into an infinite loop if its unsolvable.
                {
                    Console.WriteLine("No Match");
                    Console.ReadLine();
                    return;
                }
                j = (i * y) % x;    //Create a new j value
            
            }
            //Success
            q = i;              //i is q
            p = (z - y*q) / x;  //find p
            Console.WriteLine(p + "*" + x + " + " + q + "*" + y + " = " + z); //print
            Console.ReadLine();
            return;
        }
    }
}

Anyone with a C# compiler might like to check this (made with C# Express Beta).

And eek im going to get done for so many posts :eek:
 
Cut down on using directives to save precious memory ;). That looks about right to me. BTW anyone with the .NET Framework has the C# and VB compilers.
 
okay. let me see if I understand this.
equation:

a*x + b*y = q

user inputs a & b & q, and we solve for x znd y, using integer math only...

is that right?
 
I think I got it... maybe.

50/60 lines? seems more like 10/12 lines :\ ... unless I'm overlooking something
 
maybe it's decieving, cause I haven't actually read them real well, but those listings seem way more complicated then they should be. Meh. :\
Code:
#include <iostream>
using namespace std;
inline int negcrement(int &x) {
	x*=-1;
	return ++x;
}
int main() {
	int x,q,a,b;
	cout << "I will solve the equation ( a * x + b * y = q )" << endl;
	cout << "Enter the integer values for a, b, and q" << endl;
	cout << "Enter a >>";
	cin >> a;
	cout << "Enter b >>";
	cin >> b;
	cout << "Enter q >>";
	cin >> q;
	for (x=0;;(x>0)?(x*=-1):negcrement(x)) {
		//cout << a << " " << b << " " << q << " " << x << " " << (((a*x)-q)%-b) << endl;
		if ( (((a*x)-q)%-b) == 0 ) {
			break;
		}
	}
	cout << "\tx = " << x << endl;
	cout << "\ty = " << (((a*x)-q)/-b) << endl;
	return 0;
}
I tested it a few time with large integers, takes no percievable time. (disn't check my answers tbh :p) No overrun protection, entry type checking and othersuch.

hey, that was kinda fun.

two q: does anyone know how much of a speed penalty you get from using 'long' int math?? ...and... n/m

I was trying to figure out how to negate and increment, instead of that^ stupid negcrement inline...

weell duh. x=(-x)+1

I was trying all this -x++ crap, and it didn't work :p
 
you guys should spend less time doing algebra and more time coding games
 
news flash - there is algebra in games. and a lot more.

...you might be right though.
 
Well yes you can cut it down to fit it in there, Mine has quite a few comments and spaces and stuff so u can understand it :) (Dont u dare say my code is too long again! :p).

Also I think theoretically mine is a lot faster, as unless its a prime number it takes a shortcut :)

I would like to spend more time coding games but I don't have VS.NET2003 as it costs a fortune.
 
nbk...your problem is extremely simple.
the equation you're using is a linear equation with 2 variables which is basically the equation of a line.
perhaps the form y = ax + b is more familiar to you?
what you're trying to find is all the points that reside in this line
Your problem has infintely many solutions.
To find any one of them just input any number for one of the unknowns and solve for the other.
 
yes, but we're only looking for integer answers.

And.. yeah. i know. mine's going the simple route. eschew obfuscation, ya know? :E

actually, i wanted to go to sleep, but meh... :p
 
You can use simultaneous equations to solve for a simple nx + ny = z type equation, and better yet, some matrix transformations / vector maths would prob be the most efficient way to do it.
 
its kinda a dumb question.

my previous answer assumed u were looking for the numbers to be the same in which it give the right answer.

otherwise its just as NOP described, finding all points on a line which is trivial.
 
given a, b, and c

xa + by = c
y = (c-xa)/b

y = -(a/b)x + (c/b)

it's just a y=mx + B equation

a line with slope -(a/b) and y intercept c/b... only it's got just integers apparently.


I don't see how this is so hard....
 
Calm down the guy is only 13 :). Its not that hard if you've done GCSE maths, and if u know what modulus is. Its more just showing ways to shortcut, and how to make the code easier to read.
 
Don't yall be makin' fun of me because of my age.

Thanks to Synthos I now realize that the input formula is a Standard Form equation. Easy to do on paper, it's a system of equations. Not so easy to do in C++. Say the user inputs 10, 12, and 14:

10x + 12y = 14
y = (-5 / 6)x + (7 / 6)
x = (-6 / 5)y + (7 / 5)

y = (-5 / 6)((-6 / 5)y + (7 / 5)) + (7/6)
y = y

Actually, I just proved myself wrong. Appears the system of equations way of solving it can be fooled with certain input numbers, either that or I screwed up somewhere. Or perhaps substitution is not the best way to do it in this case.
 
N3ur0 - wilco was talking to me. We haven't solved any problems with 2 variables(looks like it is with just 1, just many more steps - algebra 1).

The examples make mine look horrible :LOL:
 
It IS only 2 variables if you fill in the ones that are user-inputted.
 
Back
Top