Find if a number is divisible by another number using recursion - python

How would I check if a number is divisible by another using recursion in python?
This is my code so far, but I would like to make it recursive.
def is_divisable(num, div):
if num % div == 0:
return True
else:
False

For educational purposes, you could keep subtracting until you reach 0 or below:
def is_divisible(num, div):
while(num > 0):
num -= div
return num == 0
Using this logic you can make it recursive (Thanks to Anonymous for pointing out the above version is not recursive):
def is_divisible(num, div):
if (num == 0):
return True
elif (num < 0):
return False
return is_divisible(num-div, div)
However, the correct way would be:
def is_divisible(num, div):
return num % div == 0

def is_divisable(num,div):
if num<div:
return num %div==0
else:
return is_divisable(num-div,div)

Related

Recursive function to reduce zeros from number

I have a mission to write a recursive function named Reduce. This function should reduce all the zeros from number and return new number.
for example:
Reduce(-160760) => -1676
Reduce(1020034000) => 1234
I started to to something but I got stuck in the condition. here's the code I wrote so far:
def Reduce(num):
while num != 0:
if num % 10 != 0:
newNum = (num % 10) +
Reduce(num//10)
def reduce(num):
if num == 0: return 0
if num < 0: return -reduce(-num)
if num % 10 == 0:
return reduce(num // 10)
else:
return num % 10 + 10 * reduce(num // 10)
String version of recursive function:
def reduce(n):
return int(reduce_recursive(str(n), ''))
def reduce_recursive(num, res):
if not num: # if we've recursed on the whole input, nothing left to do
return res
if num[0] == '0': # if the character is '0', ignore it and recurse on the next character
return reduce_recursive(num[1:], res)
return reduce_recursive(num[1:], res+num[0]) # num[0] is not a '0' so we add it to the result and we move to the next character
>>> reduce(1200530060)
12536

Python Perfect Number

In this Python Question, I should get False if the the number is not perfect. instead, I'm getting "None". What should I change?
def perfect(number):
sum = 0
is_perfect = False
if number < 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
print(perfect(8))
You should return False at the End otherwise None is getting returned implicitly:
def perfect(number):
...
for i in range(1, number):
...
return False
Hi your problem is that you have no return when you don't match if (sum == number):..
so, the simplest solution is to add an return False at the end. But also your sum condition is inside the for that's not fine because you can encounter a fake perfect
like 24... so be carefull about that condition
edit 0 is not a perfect number so add the condition to first if
def perfect(number):
sum = 0
is_perfect = False
if number <= 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
return False
I would totally reshape your code to make it a litle more clear:
def is_perfect(number):
acum= 0
if number <= 0:
return False
for i in range(1, number):
if(number % i == 0):
acum += i
return (acum == number) #return true if the condition match, False if not
#just to check function
print([(i,is_perfect(i)) for i in range(1,100) if is_perfect(i)])
#output
[(6, True), (28, True)]

Python - function returns true when a given number is a prime number or else false

Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)

A python function that finds a number's largest divisor excluding itself

When I write this code:
n = int(input('num: '))
for i in range(2, n):
if n%i == 0:
a = i
print(a)
It works without a problem.
But this creates a problem. It says
local variable a referenced before assignment
def largestDivisor(n):
for i in range(2, n):
if n%i == 0:
a = i
return a
How can I fix it?
If you call like largestDivisor(2) you won't go in the for so not in the if and you'll never define a, define it at the beginning :
def largestDivisor(n):
a = 1
for i in range(2, n):
if n % i == 0:
a = i
return a
def largestDivisor(n):
a = 1
for i in range(2,n):
if n%i==0:
a=i
return a
If the condition "n % i == 0" is never True the variable "a" will not exist, therefore you must initialize it before the loop.
def largestDivisor(n):
a = 1
for i in range(2, n):
if n%i == 0:
a = i
return a

'None' is printed when I want 'True' for input 5

In this primality test program, 'None' is printed when I input a prime, instead of 'True'. How can I get it to print 'True'?.
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s):
if (n_s % i) == 0:
return False
break
else:
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()
You need to change int(math.sqrt(n)) to int(math.sqrt(n)+1), because range runs until n_s-1. So if the input is 5, range(2,int(math.sqrt(5))) is just range(2,2), which is empty.
In addition, you need to take the return True outside of the for loop, otherwise your code may stop in a too early stage. You also don't need the break statement after return False (the function will never arrive to that line, as it will return False if it enters to that if statement).
Finally, change if (n_s % i) == 0: to if (n % i) == 0:, as you need to check if n is divisible by i (and not its square root).
Here is a more clean version:
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
First: Your break statement is redundant.
Second: For values such as 3 the for loop is never executing because value
n_s is less than 2 and since the for loop isn't executing the
python is returning the default value None(which is returned when
no value is specified).
Hence your check_n(n) function has to be
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s + 1):
if (n_s % i) == 0:
return False
return True
one liner :
check_n = lambda n : sum([i for i in range(2, int(math.sqrt(n)+1)) if n % i == 0]) == 0
don't overcomplicate things ..
Your range is (2,2) or None when you choose anything less than 9.
So to solve your first problem: add 2 to n_s (for input 3)
You also have a problem with your logic.
Your for loop should be checking that n mod i is 0, not n_s.
This should work:
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()

Categories

Resources