javadivision

Check if number is divisible by 9 without a simple modulo


Got the following assignment for school:

To check if a given number is divisible by 9 you can try taking the sum of all seperate numbers from that number. When we have the result of that sum we can easily check if it's divisible by 9.

Write a program that checks if a number is divisible by 9 using this given method. Make sure that all sums in between get written down as in the following example.

input 2656
19
10
1
no

input -9999542
47
11
2
no

input 91827
27
9
yes

I could use modulo operator in the first place, but since I'm being told to do it like that I have no idea how to work this out.

Does someone have any tips?

EDIT: not allowed to use strings or arrays.


Solution

  • int x = Integer.parseInt(args[0]), help = 0, sum= 0;
    
    if (x < 0) {
        x *= -1;
    }
    
    do {
        while(x != 0) {
            help = x % 10;
            sum += help;
            x /= 10;
        }
    
        System.out.println(sum);
    
        if(sum >= 10) {
            x = sum;
            sum = 0;
        }
    
    }while(x >= 10);
    
    if(sum / 9 == 1) {
        System.out.println("yes");
    } else {
        System.out.println("no");
    }