1
I’m having trouble solving an exercise in logic, I think I’m thinking wrong:
What I need: Given a number N 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 execute returns me:
maior_primo(7)
7
maior_primo(8)
None
I did both while
s because 1 is checking the number I reported and reducing ex: maior_primo(8)
, will test the 8 see that it has more than two splitters then will take the number I passed and subtract 1.
And the other while
will check for each number that is decreasing how many dividers it has.
Note: I can only use two functions,
while
andif
.
Do you want to show the largest or the smallest? If it is the smallest is easy,
print(2)
.– Victor Stafusa
I understood what you said, I thought wrong when I wrote it is the largest number even
– WSS
Only one left
while
decrease ofn
until I find a cousin callingehPrimo
. I could also use the sieve to pre-populate the cousins– Jefferson Quesado
@Jeffersonquesado, so it’s in the code this
while
– WSS
Not in the
ehPrimo
, but calling (present continuous/gerund)ehPrimo
. That is, inside ofmaior_primo
. And the call ofmaior_primo
outside theprint
– Jefferson Quesado
Its function
ePrimo
is not checking whether a number is prime or not, is trying to solve the problem ofmaior_primo
. Instead, make her returnTrue
if a number is prime andFalse
otherwise. Having it working, then yes you will do themaior_primo
.– Victor Stafusa