Question

I'm trying to right a program that will take a number and an n value and print out all the products of n consecutive digits within that number, and then print the greatest product of all of them.

For example, the output for 12345043 with constraint 3 would be:

1 x 2 x 3 = 6
2 x 3 x 4 = 24
3 x 4 x 5 = 60
4 x 5 x 0 = 0
5 x 0 x 4 = 0
0 x 4 x 3 = 0
Largest product is 60

My code performs abnormally, and for some reason prints (seemingly) random values as the product. I can't seem to see the bug so if someone could point it out that would be very welcome.

#include <iostream>
#include <string>

using namespace std;

int findProducts (string num, int cap); //Function to find all products and highest product

int main()
{
    string num = "12345043"; //Input
    int constraint = 3; //Number of multiples per equation
    int prod = findProducts(num, constraint); //Function to find all products and highest product
    cout << "The greatest product is " << prod << endl;
    return 0;
}

int findProducts (string num, int cap) //Function to find all products and highest product
{
    int product = 1; //Product
    int max = 0; //Variable to keep track of largest product
    for (int i = 0; i < num.length() - (cap - 1); i++) //Loop to go through all numbers in string input
    {
        for (int j = 0; j < cap; j++) //Loop through until the number of variables printed is equal to the constraint
        {
            product*=num[i + j]; //Make product equal to itself times num[i + j]
            cout << num[i + j];
            if (j != cap - 1) //If statement to cap extraneous x's being printed
            {
                cout << " x ";
            }
        }
        cout << " = " << product << endl;
        if (max < product) //If statement to check if the new product is the highest product
        {
            max = product;
        }
        product = 1; //Reset product
    }
    return max; //Return the highest product
}

Here is my output with the code above:

1 x 2 x 3 = 124950
2 x 3 x 4 = 132600
3 x 4 x 5 = 140556
4 x 5 x 0 = 132288
5 x 0 x 4 = 132288
0 x 4 x 3 = 127296
The greatest product is 140556

As you can see, very improper outputs.

Once again, any help would be much appreciated.

Thanks, Tristan

Was it helpful?

Solution

The problem is that you're multiplying product by a char corresponding to a digit in the input string:

product *= num[i + j];

You have to convert that char to the corresponding digit first. You can do this with something like that:

product *= num[i + j] - '0';

I tested it and after that change, the program gives the correct output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top