In: Computer Science
Using C #
Problem: "Tom is from the U.S. Census Bureau and greets Mary at her
door. They have the following conversation: Tom: I need to know how
old your three kids are. Mary: The product of their ages is 36.
Tom: I still don't know their ages. Mary: The sum of their ages is
the same as my house number. Tom: I still don't know their ages.
Mary: The younger two are twins. Tom: Now I know their ages!
Thanks! How old are Mary's kids and what is Mary's house
number?"
The solution is 2,2,9, therefore mary's house # is 13
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
This is the code i have thus far:
Console.WriteLine("What is the age of the first child");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("What is the age of the second child");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("What is the age of the third child");
num3 = Convert.ToInt32(Console.ReadLine());
How do I make it loop until they get the correct answer. (2,2,9) or (2,9,2) or (9,2,2)
If they get the answer wrong, I want the user keep trying again until they enter "quit"
Based on the given data, we can just obtain the possible solutions of their ages. We cannot exactly determine the ages.
Source Code:
using System;
class Sample {
static void Main() {
string val = Console.ReadLine();
int product = Convert.ToInt32(val);
int a,b;
bool flag = false;
//None of the ages is greater than the product.
//Let 'b' be the age of the elder one and 'a' be the age of younger
ones.
//Therefore, 'b' must be greater than 'a'
for(a=1;a<=product;a++){
for(b=1;b<=product;b++){
if(a<b && a*a*b == product){
flag = true;
Console.WriteLine();
Console.WriteLine("Ages are " + a + ", " + a + " and " + b);
Console.WriteLine("Mary\'s house number is " + (2*a + b));
}
}
}
if(!flag){
Console.WriteLine("I cannot find their ages");
}
}
}
Output:
Please appreciate the solution if you find it helpful.
If you have any doubts in the solution, feel free to ask me in the comment section.