def check_prime(x):
for i in range(2,x):
if x%i==0:
return False
else: return True
Why is this code not working properly. This code returns true even for some non prime numbers. eg:- 9 , 25 ,...
You are returning True right away when you find one number that doesn't divide x, which is wrong. You're supposed to return True when all number greater or equal to 2 and less than x doesn't divide x. To fix this, remove the else code, and return True after the for loop is over.
Here's the full code:
def check_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
Related
I was presented with a problem where I had to create an algorithm that takes any given input integer of even length and, based on the input, determines whether the sum of the first n digits is equal to the sum of the last n digits, where each n is the equal to the length of the number divided by two (e.g. 2130 returns True, 3304 returns False).
My solution, which works but is rather unwieldy, was as follows:
def ticket(num):
list_num = [int(x) for x in str(num)]
half_length = int(len(list_num)/2)
for i in range(half_length*2):
first_half = list_num[0:half_length]
second_half = list_num[half_length::]
if sum(first_half) == sum(second_half):
return True
else:
return False
In an effort to improve my understanding of list comprehensions, I've tried to look at ways that I can make this more efficient but am struggling to do so. Any guidance would be much appreciated.
EDIT:
Thank you to jarmod:
Reorganised as so:
def ticket(num):
list_num = [int(x) for x in str(num)]
half_length = int(len(list_num)/2)
return sum(list_num[0:half_length]) == sum(list_num[half_length::])
ticket(1230)
You can remove the unnecessary assignment and loops to create a shorter, more pythonic solution:
def ticket(num):
half_length = int(len(list_num)/2)
first_half = sum(list(num[:half_length]))
second_half = sum(list(num[half_length:]))
return first_half == second_half
It can be further shortened though, which isn't as readable:
def ticket(num):
return sum(list(num[:len(num)//2])) == sum(list(num[len(num)//2:]))
Im trying to solve a problem where I have to use a for loop in solving if a number is prime or not. It seems like it only picks up if the number is divided by two to determine if it is prime or not. My code doesn't pick up if it is divisible by 3 and up though...
Here is my code:
def isPrime(num):
for i in range (2,num):
if (num%i) !=0:
return True
else:
return False
isPrime(15)
I know 15 is not a prime number but it is returning True instead of False. Can anyone help? Thanks
OP's algorithm always exits on the first iteration.
Instead, loop less often and only exit loop when a divisor is found. Also account for values less than 2.
def isPrime(num):
for i in range [2,isqrt(num)]:
if (num%i == 0) return False
if (num < 2) return False
return True
How to find prime numbers?
Prime numbers are the numbers that are bigger than one, and are divisible only by themselves and one. One way to determine whether or not a number is a prime number is as follows:
->if the number < 2, then return False
->if the number is 2, then return True
->for each value of i, where i >=2 and i < number:
if the number is divisible by i, then return False
->return True
My current code:
def is_prime(number):
if number == 2:
return True
elif number < 2:
return False
else:
for i in range(2, number):
if number % i == 0:
return False
else:
return True
def main():
print(is_prmie(1))
print(is_prmie(4))
print(is_prmie(7))
Some syntax problems I don't know how to solve.
Can someone please help?
Thanks TA!
I suggest the following:
from math import sqrt
def is_prime(x):
if x < 2:
return False
if x % 2 == 0:
return x == 2
i = 3
while i <= sqrt(x):
if x % i == 0:
return False
i += 2
return True
Things to note:
The only even prime is 2. The loop is restricted to odd numbers.
Only factors up to and including the square root must be tested. Because if x = y * z and y ≥ sqrt(x) then z ≤ sqrt(x)
Only one return statement in the loop. You can exit early on a non prime, but you must complete the loop to be sure the number is prime.
You need to call the main() and write is_prime() correctly.
def is_prime(number):
if number == 2:
return True
elif number < 2:
return False
else:
for i in range(2, number):
if number % i == 0:
return False
else:
return True
def main():
print(is_prime(1))
print(is_prime(4))
print(is_prime(7))
main()
Spelling of is_prime at the time of method call is wrong. Also, you haven't mke a call to the method main at the end.
Small improvement:
for i in range(2, number):
this line can be as below as we don't need to check divisibility of the number after its half:
for i in range(2, (number/2)):
e.g. for checking 24 is prime or not, we need to check only upto 12 because it will never be divisible by number greater than 12.
<?php
// PHP code to check wether a number is prime or Not
// function to check the number is Prime or Not
function primeCheck($number){
if ($number == 1 || $number == 2 || $number % 2 !== 0) {
echo "Prime";
}
else if ($number % 2 == 0)
{
echo "Not Prime";
}
}
echo primeCheck(5);
For instance:
8 > 10 = true, since 8 is divisible by 2 three times and 10 only once.
How can I compare two integers from any range of numbers? Are the modulo and divide operator capable of doing this task?
Use binary caculate to judge it
def devided_by_two(i)
return i.to_s(2).match(/0*$/).to_s.count('0')
end
To make integer divisibility by 2, just transcode it to binary and judge how many zero from end of banary number. The code I provide can be more simple I think.
Yes, they are capable. A number is even if, when you divide it by two, the remainder is zero.
Hence, you can use a loop to continuously divide by two until you get an odd number, keeping a count of how many times you did it.
The (pseudo-code) function for assigning a "divisibility by two, continuously" value to a number would be something like:
def howManyDivByTwo(x):
count = 0
while x % 2 == 0:
count = count + 1
x = x / 2 # make sure integer division
return count
That shouldn't be too hard to turn into Ruby (or any procedural-type language, really), such as:
def howManyDivByTwo(x)
count = 0
while x % 2 == 0
count = count + 1
x = x / 2
end
return count
end
print howManyDivByTwo(4), "\n"
print howManyDivByTwo(10), "\n"
print howManyDivByTwo(11), "\n"
print howManyDivByTwo(65536), "\n"
This outputs the correct:
2
1
0
16
Astute readers will have noticed there's an edge case in that function, you probably don't want to try passing zero to it. If it was production code, you'd need to catch that and act intelligently since you can divide zero by two until the cows come home, without ever reaching an odd number.
What value you return for zero depends on needs you haven't specified in detail. Theoretically (mathematically), you should return infinity but I'll leave that up to you.
Notice that you will likely mess up much of your code if you redefine such basic method. Knowing that, this is how it's done:
class Integer
def <=> other
me = self
return 0 if me.zero? and other.zero?
return -1 if other.zero?
return 1 if me.zero?
while me.even? and other.even?
me /= 2
other /= 2
end
return 0 if me.odd? and other.odd?
return -1 if me.odd?
return 1 if other.odd? # This condition is redundant, but is here for symmetry.
end
end
number = -5
case number
when number < 0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
end
...
I expected it to return "Please enter a number greater than 0", but instead it returned nil. Why is that? How can I check if the number is less than 0?
When you give a variable to case, it's compared against each when clause with the === method. The first === to return true will be the branch that's executed.
In your case, number < 0 is evaluating to true, and -5 === true is false!
What you want to do is either leave the number off of the case, and make all of the when clauses boolean:
case
when number < 0
return "Please enter a number greater than 0."
when number.between?(0, 1)
return false
when number == 2
return true
end
Or leave the number on, but make all of the whens values that you can compare against:
case number
when -Float::INFINITY..0 # or (-1.0/0)..0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
end
when number < 0 will be the same as when true in this case, because number is indeed less than zero, and the when will not be entered since -5 != true.
You could try
when (-1.0/0)..0 # negative Infinity to 0
Or, if you're using 1.9.2 or above:
when -Float::INFINITY..0