Skip to content Skip to sidebar Skip to footer

Efficient Implementation For: "Python For Else Loop" In Java

In Python there is an efficient for else loop implementation described here Example code: for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x b

Solution 1:

It's done like this:

class A {
    public static void main(String[] args) {
        int n = 13;
        found: {
            for (int x : new int[]{2,3,4,5,6,7,8,9,10,11,12})
                if (n % x == 0) {
                    System.out.println("" + n + " equals " + x + "*" + (n/x));
                    break found;
                }
            System.out.println("" + n + " is a prime number");
        }
    }
}

$ javac A.java && java A
13 is a prime number

Solution 2:

When I need to do something like this, if no extra information is needed, I typically try to break it out into a separate method - which can then return true/false or alternatively either the value found, or null if it's not found. It doesn't always work - it's very context-specific - but it's something worth trying.

Then you can just write:

for (...) {
    if (...) {
       return separateMethod();
    }
}
return null; // Or false, or whatever

Solution 3:

No. That's the simplest. It's not that complicated, it's just syntax.


Solution 4:

Since java8 there is a way to write this with "nearly no" code:

if(IntStream.range(2, n).noneMatch(x -> n % x == 0)) {
   System.out.println(n + " is a prime number");
}

BUT: this would be less efficient than the classical looping-with-break-and-flag method.


Solution 5:

No, there is no mechanism like this in Java


Post a Comment for "Efficient Implementation For: "Python For Else Loop" In Java"