How to Find Prime Number - syntax

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);

Related

How to use for loop to find a prime number?

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

Pseudocode - What is wrong about this

I AM TRYING TO FIND THE ERROR
The code is supposed to find out if a positive integer entered by a user is exactly divisible by the number 3.
n = userinput
WHILE n ≥ 0
n = n - 3
ENDWHILE
You're using greater than OR EQUAL TO so you won't break out of the loop on n = 0, only n = -3 which then triggers your ELSE statement. The EQUAL TO aspect takes you a step too far.
Answering the comment:
Use > instead of >=. Basically the code as written will never allow n to equal 0 at the time the condition is evaluated. Trace each step of the loop using a number like 3.
N = 3
//first pass
WHILE (3 >= 0) // true
n = 3-3 //n now 0
//second pass
WHILE (0 >= 0) //True, 0 is equal to 0
n = 0-3 //n now -3
//third pass
WHILE(-3 >= 0) //False break out of loop
IF(-3 == 0) // false so we jump to the else
ELSE: 3 is not divisible by 3.
One quick way to easily spot check your loops that aren't performing as expected is to just manually run through them with an easy input.

Smallest_multiple function in MATLAB

Hi I am having problems with the following function in Matlab. Can some please help?
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Write a function called smallest_multiple that returns a uint64, the smallest positive number that is evenly divisible by all of the numbers from 1 to n where n is a positive integer scalar and is the only input argument of the function. If the result would be greater than what can be represented as a uint64, the function returns 0. (Inspired by Project Euler.)
Below is the code I wrote for the function but it gives error
Feedback: Your function made an error for argument(s) 2
Your solution is _not_ correct.
Help please...
function [answer]=smallest_multiple(n)
limit = 1e10;
N = 20;
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)
Your function looks correct. However the argument you pass is a lowercase n instead of an uppercase N, which you use during your code.
So the correct function (with limit as argument) is
function [answer]=smallest_multiple(N,limit)
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)

Why does my number only stay at 2 for the Collatz sequence?

I am trying to make a program that calculates when a number will reach zero using the Collatz sequence. Here is my code for that program:
import time
def run(z):
while z != 1:
if isEven(z) == True:
z = z/2
print z
else:
z = (3*z)+1
print z
else:
print 'Got one!'
z = z+1
print 'Trying for %d...' %(z)
time.sleep(0.1)
run(z)
def isEven(number):
return number % 2 == 0
run(z)
However, the z never goes above 2, it only keeps printing:
Got one!
Trying for 2...
1
Got one!
Trying for 2...
1
And so on... Can anyone tell me what I am doing wrong?
The Collatz conjecture is that you will reach one, not zero; when you reach one, you should stop. Also, you have an odd combination of while loop and recursive calling. A very simple recursive implementation:
def collatz(n):
print(n)
if n == 1: # base case
print("Done!")
else:
if n % 2: # odd number
collatz((3 * n) + 1)
else: # even number
collatz(n / 2)
or iterative version:
def collatz(n):
while n != 1:
print(n)
if n % 2: # odd number
n = (3 * n) + 1
else: # even number
n /= 2
print(n)
print("Done!")
If you want to analyse how long a number takes to reach one, you can rejig one of those implementations, e.g.:
def collatz(n):
count = 0
while n != 1:
count += 1
if n % 2: # odd number
n = (3 * n) + 1
else: # even number
n /= 2
return count
You can then call this function, working through the integers, creating the Collatz sequence for each one, for example:
seq_len = [(n, collatz(n)) for n in range(1, 101)]
Once z is 1, you exit the while loop, entering the else, which calls run(2), which sets z back to 1, which calls run(2) and so on and so on.

Ruby - determine if a number is a prime

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.
So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?
def is_prime n
for d in 2..(n - 1)
if (n % d) == 0
return false
end
end
true
end
def is_prime2 n
foundDivider = false
for d in 2..(n - 1)
foundDivider = ((n % d) == 0) or foundDivider
end
not foundDivider
end
It's because = is of higher precedence than or. See Ruby's operator precedence table below (highest to lowest precedence):
[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end
The problematic line is being parsed as...
(foundDivider = ((n % d) == 0)) or foundDivider
...which is certainly not what you mean. There are two possible solutions:
Force the precedence to be what you really mean...
foundDivider = (((n % d) == 0) or foundDivider)
...or use the || operator instead, which has higher precedence than =:
foundDivider = ((n % d) == 0) || foundDivider
Ruby comes with predefined classes such as Prime. All you have to do is to require that class into your project.
require 'prime'
Than, you can use some of the Prime methods such as first to get first x prime elements:
Prime.first(5) # Ret => [2, 3, 5, 6, 11]
Or you could do something like this:
Prime.each(100) do |prime|
p prime # Ret => [2, 3, 5, 7, 11, ..., 97]
end
I hope you find this useful.
def prime(n)
return false if n < 2
(2..n/2).none?{|i| n % i == 0}
end
A prime number is any number that has no positive divisors other than itself and 1.
def prime? n
(2..Math.sqrt(n)).none? {|f| n % f == 0}
end
The range of factors should start at 2 and end at the square root of n because every number is divisible by one and no number is divisible by two numbers greater than its square root.
Explanation: A non-prime number is the product of two numbers.
n = f1 * f2
n is always divisible by its square root so both f1 and f2 cannot be greater than the square root of n, otherwise f1 * f2 would be greater than n. Therefore, at least one factor is less than or at most equal to Math.sqrt(n). In the case of finding prime numbers its only necessary to find one factor so we should loop from 2 to the square root of n.
Find prime numbers from loop:
def get_prime_no_upto(number)
pre = [1]
start = 2
primes = (start..number).to_a
(start..number).each do |no|
(start..no).each do |num|
if ( no % num == 0) && num != no
primes.delete(no)
break
end
end
end
pre + primes
end
and use it as below:
puts get_prime_no_upto(100)
Cheers!
Here is code that will prompt you to enter a number for prime check:
puts "welcome to prime number check"
puts "enter number for check: "
n = gets
n = n.to_i
def prime(n)
puts "That's not an integer." unless n.is_a? Integer
is_prime = true
for i in 2..n-1
if n % i == 0
is_prime = false
end
end
if is_prime
puts "#{n} is prime!"
else
puts "#{n} is not prime."
end
end
prime(n)
Based on the answer by Darmouse but including edge cases
def prime? (n)
if n <= 1
false
elsif n == 2
true
else
(2..n/2).none? { |i| n % i == 0}
end
end
FYI - re: DarkMouses prime method above - I found it really helpful, but there are a few errors (I think!) that need explaining:
It should be parentheses rather than square brackets... Otherwise you get a TypeError
Range can't be coerced into Fixnum (TypeError)
Secondly, that first colon before 'false' would cause an error too. It's incorrect syntax, as far as I know. Get rid of it.
Lastly, I think you got it the wrong way round?? If you correct the errors I mentioned, it returns true if it ISN'T a prime, and false if it IS.
You can drop the ternary operator altogether I think, and just do:
def prime?(n)
(2..n/2).none?{|i| n % i == 0}
end
Obviously it doesn't cover the edge cases (0,1,2), but let's not split hairs.
...For those who enjoy hairsplitting, here is my full solution to this problem:
def prime?(n)
return false if n < 2
(2..Math.sqrt(n)).none? {|num| length % num == 0}
end
Hope I didn't miss anything :)
This is a little bit off topic according to the details, but correct for the title : using bash integration in ruby you could do :
def is_prime n
`factor #{n}`.split.count < 3
end
bash factor function returns a number plus all of his factors, so if the number is prime, there will be two words count.
This is usefull for code golf only.
I tried this and it worked:
def prime?(n)
return false if n < 2
return true if n == 3 || n == 2
if (2...n-1).any?{|i| n % i == 0}
false
else
true
end
end
def prime?(n)
if n <= 1
return false
else (2..n-1).to_a.all? do |integer|
n % integer != 0
end
end
end
From my prime? lab. Started with eliminating all integers less than or equal to 1.
def prime(n)
pn = [2]
if n < 2
return false
else
(2..n).each do |i|
not_prime = false
(2..Math.sqrt(i).ceil).each do |j|
not_prime = true if i % j == 0
end
pn.push(i) unless not_prime
end
end
return pn
end
p prime(30) gives
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
It will return true if the number is prime.
def prime_number(number)
(2..(number-1)).each do |value|
if (number % value) == 0
return false
end
return true
end
end
puts prime_number(4)
class Object
private
def prime? num
if (2..3).include? num
return true
else
!num.even? and num % 3 != 0 and num > 1
end
end
end
prime? 1
prime? 2
prime? 9
prime? 17
** FOR A SIMPLE SHORTED METHOD**
FIRST INSTALL PRIME GEM
require 'prime'
`p prime.first(20)`
Now save that file as your desired name, this will generate the first 20 prime numbers Automatically!! :-)

Resources