0

I have been working on a program to take integer x and find any numbers whose sum of the digits multiplied by x equals the number. my code has worked for numbers 2, 3, and 4, but beyond that is returns various errors regardless of what i am doing. any help would be greatly appreciated.

my code:

package SumOfTheDigits;

public class Test
{
    public static void main(String[] args) throws java.lang.Exception
    {
         int a = 3;
         int x = 1;
         int solutions =  (9 - ((((10 * x) - (a * x))/(a - 1)) % 9))/(((10 * x) - 
                          (a * x))/(a - 1));

         for(int z = 1; z < solutions + 2; z++)
         {
             if((z * 10) + ((10 * z) - (a * z))/(a - 1) == a * (z + ((10 * z) - 
                   (a * z))/(a - 1)))
             {
                 System.out.println(z + "" + ((10 * z) - (a * z))/(a - 1));
             }      
         }
    }
}
burntsugar
  • 57,360
  • 21
  • 58
  • 81

1 Answers1

1

You are getting / by zero exceptions because your numbers are stored as integers, that means when you would normally get a decimal value < 1 you actually get 0. Take this example from your code

int a = 15;
int x = 1;
// with the bottom half of your equation
int solutions = ....other math.../(((10 * x) - (a * x))/(a - 1))

// (((10 * 1) - (15 * 1))/(15 - 1)) = (-5/14) - > converted to integer = 0

So..

int solutions = ....other math.../0

and an error is thrown. What you should do is convert all your int to doubles to allow the equation to be evaluated correctly.

double a = 10;
double x = 1;
double solutions = ....;

Also have some faith in order of operations and remove some parentheses :), theres so many it is a headache to look at

double temp = (10*x - a*x)/(a - 1);
double solutions = (9 - (temp % 9))/temp;
ug_
  • 11,267
  • 2
  • 35
  • 52
  • do you have any idea how i could expand this to work with a value of x for any number of digits? – Alexander Gulea Jan 30 '14 at 02:23
  • @AlexanderGulea I couldn't tell you because I have no idea what you are even trying to do with this program :). Just think about it for a bit, throw your best shot at it and keep working at it. Im sure you will find a way to make it happen if you really give it a good try. – ug_ Jan 30 '14 at 02:28
  • i wanted to get the program to return values when the input is ten or greater. so far input that is greater then 10 the program returns nothing or it returns a strange decimal value. – Alexander Gulea Jan 30 '14 at 03:02