this post was submitted on 31 Oct 2024
385 points (99.0% liked)

196

16774 readers
2311 users here now

Be sure to follow the rule before you head out.

Rule: You must post before you leave.

^other^ ^rules^

founded 2 years ago
MODERATORS
 
(page 2) 8 comments
sorted by: hot top controversial new old
[–] [email protected] 54 points 2 months ago* (last edited 2 months ago) (2 children)
import re

def is_even(i: int) -> bool:
    return re.match(r"-?\d*[02468]$", str(i)) is not None
load more comments (2 replies)
[–] [email protected] 14 points 2 months ago (2 children)
If number%2 == 0: return("Even")
Else: return("odd") 
load more comments (2 replies)
[–] [email protected] 22 points 2 months ago (4 children)

Ask AI:

public static boolean isEven(int number) {
    // Handle negative numbers
    if (number < 0) {
        number = -number; // Convert to positive
    }
    
    // Subtract 2 until we reach 0 or 1
    while (number > 1) {
        number -= 2;
    }
    
    // If we reach 0, it's even; if we reach 1, it's odd
    return number == 0;
}
load more comments (4 replies)
[–] [email protected] 18 points 2 months ago (1 children)

When you sacrifice memory for an O(1) algorithm.

In this case still O(n)

load more comments (1 replies)
[–] [email protected] 45 points 2 months ago (3 children)

Just divide the number into its prime factors and then check if one of them is 2.

[–] [email protected] 13 points 2 months ago (2 children)

I remember coding actionscript in Flash and using modulo (%) to determine if a number was even or odd. It returns the remainder of the number divided by 2 and if it equals anything other than 0 then the number is odd.

[–] [email protected] 19 points 2 months ago

I believe that's the proper way to do it.

load more comments (1 replies)
[–] [email protected] 20 points 2 months ago* (last edited 2 months ago) (4 children)

or divide the number by two and if the remainder is greater than

-(4^34)

but less than

70 - (((23*3*4)/2)/2)

then

true
load more comments (4 replies)
load more comments (1 replies)
load more comments
view more: ‹ prev next ›