Jerry
Jerry

Reputation: 3

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);        
        }
   }

Upvotes: 0

Views: 224

Answers (2)

laune
laune

Reputation: 31300

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.

Upvotes: 1

jacob_b
jacob_b

Reputation: 200

The first method you wrote is a little better but honestly it's not going to make a noticeable difference in speed or efficiency. Also I would suggest not omitting the curly brackets on your if statements and put the statements on a new line, the approach you are taking is considered bad form and according to Oracles code conventions can be error prone although I have never seen an error result from this.

For reference Code Conventions for Java

Upvotes: 0

Related Questions