student
student

Reputation: 9

Generate 3 digits numbers according to specific constraints

If I take 3 numbers A B C with 3 digits each (between 100-999) and do :

A + B = C

If all nine digits used are non zero and different from each other ( 1-2-3-4-5-6-7-8-9) then the sum of the digits of C will always be 18.

ex : 152 + 487 = 639   -----> 6+3+9 = 18 
     357 + 462 = 819 = -----> 8+1+9 = 18 

I need my program to show all cases of numbers A,B and C that respect this relation. I am unsure how to tackle this problem. I was thinking of either using an outer for loop and a inner for loop or using the rand function but I am unsure how to give the necessary conditions to any of these methods.

Upvotes: 0

Views: 239

Answers (3)

NathanOliver
NathanOliver

Reputation: 180500

My approach would be to go through all permutations of "123456789" using std::next_permutation and check that the first 3 digits plus the second 3 digits minus the last 3 digits equals 0. Something like:

int main() 
{
    std::string numbers = "123456789";
    int a, b, c;
    do
    {
        a = std::stoi(numbers.substr(0, 3));
        b = std::stoi(numbers.substr(3, 3));
        c = std::stoi(numbers.substr(6, 3));
        if (a + b == c)
            std::cout << a << " + " << b << " = " << c << "\n";
    } while (std::next_permutation(numbers.begin(), numbers.end()));
}

Upvotes: 0

CinchBlue
CinchBlue

Reputation: 6190

  1. Find all 3-digit number pairs whose sums of digits are 18.
  2. Add the numbers; discard if sum not equal to 999.
  3. Discard entries where A1 == B2 and A2 == B1

Optimizations:

  • There is only one unique number B for each number A such that A + B == 999.

  • For every number A and B the differcence between the current A and the next A and the current B And the next B is always greater than 8.


Use if conditions for the required mathematic conditions. Simple as that.

Iterate through all the 3-digit number pairs by using a for-loop or paralleize by using async

I'm on mobile so I can't code; I'll edit this if you need more.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

Enumerate all the 9! (=362880) permutations of the 9 digits, then for each permutation check whether it meets the requirements.

1 2 3 4 5 6 7 8 9    one permutation
----- ----- -----
  A     B     C      chunked to these numbers (simple base10 math)

For generating the permutations you can use next_permutation.

Upvotes: 1

Related Questions