Is_prime: Why isn't this working?


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096


I fed this into the visualization tool, and it does not seem to be processing the syntax in the 2nd if statement


Seems like x/n - int (x/n) should do effectively the same thing as x % n, no?


def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    for n in range(2, x):
        if x / n - int(x / n) == 0:
            return False
        else:
            return True


#2

No, because when the division involves to integers, python floors the number (rounds down), so:

x / n

lets say we want to see if 3 is a prime number, then the first case for the loop is two:

3 / 2

is one, given python rounds down.

if you do:

float(x) / n

Then it works just like the modulo operator


#3

Thank you for your reply!

So can you show me an example of how to use this approach properly?
The math is valid. The issue I am having is with the conventions (float vs integer).
I think that if I can figure this out I will have a much better understanding of when/how to use each class, respectively.

To try to clarify, I just threw this together:

def divide_by_3(y):
    result = (y / 3)
    print result
    return result

divide_by_3(float(10))

Point is that when you start with a float input, python will happily give you a result with a decimal point. Why can't I get it to do that is_prime code, and use this in my prime discerning loop?


#4

Ok! I think I answered my own question! Not the prettiest code, but it gets the job done!

Main issue was indentation with my final else statement. Before I deleted the last indent the program was exiting the loop prematurely.

Feedback would still be appreciated. Thank you!

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    for n in range(2, x):
        integer = int(x/n)
        y = float(x)
        w = float(n)
        decimal = (y/w)
        if (decimal - integer) == 0:
            return False
    else:
        return True
is_prime(int(raw_input('Enter a number to determine if it is prime:')))

#5

you can shorten this a lot:

        integer = int(x/n)
        y = float(x)
        w = float(n)
        decimal = (y/w)
        if (decimal - integer) == 0:

to:

if float(x) / n % x / n == 0

more parentheses might be required, not sure what the order of operations is here.

given x/n will be floored (round down), you only have to use one float() somewhere to make this work


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.