Search code examples
javafactorization

Efficient way to determine if b is a factor of a?


this is part of a calculator program that I'm currently making, this part determines if b is a factor of a. Also I am new to Java this makes my third day learning it's syntax. Anyway, I was wondering which way is more efficient to determine if b is a factor of a. Is it to us the modulus operator (%) or my second method ???

also if there's a more efficient way than the two methods I came up with please show.

// for now I want the result to print out in the console
public class factornot {
    public static void main(String args[]) {
        int a = 56, b = 3; // just for testing purposes!
        if((a != 0) && (a % b) == 0) System.out.println(b + " is a factor of " + a); 
        else System.out.println(b + " is not a factor of " + a);
        // short-circuit and prevents a divide by zero error!


        // is this better or worse, faster or slower ???

        int d = (a / b), e = (d * b); 
        if((a - e) == 0) System.out.println(b + " is a factor of " + a); 
        else System.out.println(b + " is not a factor of " + a);        
        }
   }

Solution

  • There can't be much difference as far as the basic computations are concerned. To establish that a == 0 mod b, a division has to be performed and the remainder calculated by a subtraction.

    The operator % however, offers the compiler the opportunity to do it all "under the hood", not requiring the stores and fetches (presumably optimzed to whatever can be short-cut) of the second version.

    Besides: the less code, the less chance for an error. The direct way provides good readability.