Check the largest prime number - using only while and if

0

I'm having trouble solving an exercise in logic, I think I'm thinking wrong:

What I need: Given an N number show the largest prime number up to N.

The code I've made so far is this:

def maior_primo(n):
    print(ePrimo(n))


def ePrimo(k):
    aux = k
    i = 1
    divisores = 0
    while(aux >= 1):
        while(i <= aux):
            if(aux % i == 0):
                divisores += 1
                i += 1
            else:
                i += 1
        if(divisores < 3):
            return aux
        else:
            aux -= 1

But when I run it returns me:

maior_primo(7)
7

maior_primo(8)
None

I made the two% s of% s because 1 is checking the number I reported and reducing ex: while , will test 8 see that it has more than two divisors so I will get the number I passed and subtract 1. p>

And the other maior_primo(8) will check for each number that decreases how many divisors it has.

  

Note: I can only use two functions, while and while .

    
asked by anonymous 14.11.2017 / 19:25

1 answer

3

Your ePrimo function is not checking whether a number is prime or not, it is trying to solve the maior_primo problem. Instead, make it return True if a number is prime and False otherwise. Having it working, then you will do maior_primo .

Another thing to keep in mind is that if k is a number it is composed, so the biggest factor it can have is its square root. You do not need to calculate the square root directly, just check for any possible i divisor, if i 2 . >

Here's the code (including testing):

def maior_primo(n):
    aux = n
    while aux > 2:
        if eh_primo(aux):
            return aux
        aux -= 1
    return 2

def eh_primo(k):
    i = 2
    while i * i <= k:
        if k % i == 0:
            return False
        i += 1
    return True

print('Maior primo ate 8: ' + str(maior_primo(8)))
print('Maior primo ate 7: ' + str(maior_primo(7)))
print('Maior primo ate 100: ' + str(maior_primo(100)))
print('Maior primo ate 60: ' + str(maior_primo(60)))
print('Maior primo ate 61: ' + str(maior_primo(61)))
print('Maior primo ate 3: ' + str(maior_primo(3)))
print('Maior primo ate 2: ' + str(maior_primo(2)))
print('Maior primo ate 1: ' + str(maior_primo(1)))
print('Maior primo ate 0: ' + str(maior_primo(0)))

Here is the output produced:

Maior primo ate 8: 7
Maior primo ate 7: 7
Maior primo ate 100: 97
Maior primo ate 60: 59
Maior primo ate 61: 61
Maior primo ate 3: 3
Maior primo ate 2: 2
Maior primo ate 1: 2
Maior primo ate 0: 2

See here working on ideone.

    
14.11.2017 / 20:08