To generate laundau's prime numbers using python - python

I want to generate list of primes of the format x2+1 but I am not getting any output.
My code:
def LPrime(n):
for i in range(1,n):
x = i**2+1;
for j in range(2,x):
if x % j != 0:
print(x,i)
Please tell me what am I doing wrong.
The expected output should be something like
2,1
5,2
and so on
Also I am not able to execute it properly, I am using Ubuntu 22.04
There is no output when I try to

If if x % j == 0: you have a divisor. and j will not be 1 or x. So you should mark p as False (there is no prime). else, it is a prime; print it.
def LPrime(n):
for i in range(0, n):
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
Don't forget to call it
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
If you want n primes, use a while loop:
def LPrime(n):
count = 0
i = 0
while count < n:
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
count += 1
i += 1
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
Prime = 17, i = 4

Related

Getting False with my Def, What is wrong with my code?

def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(n, n+1):
if n % i ==0:
nb.append(i)
sum1 = sum(nb) - nb[-1]
if sum1 > n:
return True
else:
return False
n = int(input("n:"))
print(richNumber(n))
I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100
With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False
for i in (n, n+1)
Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)
Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False

Is there any way to fix my python code being stuck?

primeNum = []
def isPrime(y):
i = 2
while(i < number):
if number % i == 0:
return False
i = i + 1
return True
def printNum(x):
k = 2
while k <= x:
if isPrime(k):
primeNum.append(k)
k = k + 1
printNum(number)
numOfPrime = len(primeNum)
sum = 0
j= 0
while j < numOfPrime:
sum += primeNum[j]
j = j + 1
print(sum)
When I run the code it just gets stuck on the input. I have tried everything but it doesn't give me an error unless I press CTRL + C then it will tell me Traceback.....
the line k = k + 1 in the function printNum was out of the while loop , making it an infinite loop,same goes for i = i + 1 in isPrime and j = j + 1 in the last loop, so i fixed it for you
additionally, the function isPrime had some bugs
it referred to number instead of y in a few places so I fixed that too
this should do the trick:
primeNum = []
number=10
def isPrime(y):
i = 2
while (i < y):
if y % i == 0:
return False
i = i + 1
return True
def printNum(x):
k = 2
while k <= x:
if isPrime(k):
primeNum.append(k)
k = k + 1
printNum(number)
numOfPrime = len(primeNum)
sum = 0
j = 0
while j < numOfPrime:
sum += primeNum[j]
j = j + 1
print(sum)
print("end")

I need to make a list of of the multiples of 3 and 5 based on a previous number list Example: input[8,5,3.10] output[5,3,10] but output is not adding

def multiplos(listOfNumbers):
Multiples =[]
i=0
x= len(listOfNumbers)
while i < x:
if len(listOfNumbers[i]) % 5 == 0:
Multiples.append(listOfNumbers[i])
i+=1
return Multiples
numeros = listaNum()
print(multiplos(numeros))
This should work:
def multiplos(listOfNumbers):
Multiples = []
i = 0
x = len(listOfNumbers)
while i < x:
if listOfNumbers[i] % 5 == 0 or listOfNumbers[i] % 3 == 0:
Multiples.append(listOfNumbers[i])
i += 1
return Multiples
Stylistically, it's probably better to write it as a for-loop instead of a while-loop:
def multiplos(listOfNumbers):
Multiples = []
for n in listOfNumbers:
if n % 5 == 0 or n % 3 == 0:
Multiples.append(n)
return Multiples
You could even use a list comprehension instead:
def multiplos(listOfNumbers):
return [n for n in listOfNumbers
if n % 5 == 0 or n % 3 == 0]

Printing the sum of prime divisors of each number in a given range in python

Here's my code for printing the sum of prime divisors of each number between 18 to 25. But it is only printing 5.
For example:
18 has prime factors 2, 3 hence sum = 5,
19 is prime, hence sum of factors = 0,
20 has prime factors 2 and 5, hence sum = 7,
21 has prime factors 3 and 7, hence sum = 10,
22 has prime factors 2 and 11, hence sum = 13,
23 is prime. hence sum = 0,
24 has prime factors 2 and 3, hence sum = 5,
25 has prime factor 5, hence sum = 5
Therefore, it should print [5,0,7,10,13,0,5,5]
I believe I should use break statement but i tried it didn't work. As I am beginner in python, any kind of help much appreciated.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if (n % i == 0):
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
return True
def summ(l, r):
summ = 0
arrayofdivisors = []
arrayofsum = []
# iterate from lower to upper
for i in range(l, r + 1) :
# if i is prime, it has no factors
if (isPrime(i)) :
continue
for j in range(2, i):
# check if j is a prime factor of i
if (i % j == 0 and isPrime(j)) :
arrayofdivisors.append(j)
if(len(arrayofdivisors)>1):
ans = sum(arrayofdivisors)
arrayofsum.append(ans)
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))
Try this
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def Sum(N):
SumOfPrimeDivisors = [0] * (N + 1)
for i in range(2, N + 1) :
if (SumOfPrimeDivisors[i] == 0) :
for j in range(i, N + 1, i) :
SumOfPrimeDivisors[j] += i
return SumOfPrimeDivisors[N]
arr=[]
for i in range(18,26):
if isPrime(i):
arr.append(0)
else:
arr.append(Sum(i))
print(arr)
It's almost impossible to tell because of the way you've formatted things, but the problem here is that your "return" statement is indented one position too far. Thus, you return at the end of the first loop, before it has a chance to check anything else. Un-indent the return arrayofsum and it should work.
Then, you are initializing arrayofdivisors outside the main loop, so it just kept getting larger and larger. Then, you weren't adding 0 to the list for prime numbers, as your spec required.
Note that if statements in Python do not need parentheses, like they do in C.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if n % i == 0:
print(n,'not prime')
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
print(n,"prime")
return True
def summ(l, r):
# iterate from lower to upper
arrayofsum = []
for i in range(l, r + 1) :
arrayofdivisors = []
# if i is prime, it has no factors
if isPrime(i):
arrayofsum.append(0)
continue
for j in range(2, i):
# check if j is a prime factor of i
if i % j == 0 and isPrime(j):
arrayofdivisors.append(j)
arrayofsum.append( sum(arrayofdivisors) )
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))

Collatz conjecture sequence

The Collatz conjecture
what i am trying to do:
Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].
background on collatz conjecture:
Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
What I have so far:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x= x/2
else:
x= 3*x+1
return seq
When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.
You forgot to append the x values to the seq list:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
seq.append(x) # Added line
return seq
Verification:
~/tmp$ python collatz.py
[6, 3, 10, 5, 16, 8, 4, 2, 1]
def collatz_sequence(x):
seq = [x]
while seq[-1] > 1:
if x % 2 == 0:
seq.append(x/2)
else:
seq.append(3*x+1)
x = seq[-1]
return seq
Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.
>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)
Here's another way of doing it:
while True:
x=int(input('ENTER NO.:'))
print ('----------------')
while x>0:
if x%2==0:
x = x/2
elif x>1:
x = 3*x + 1
else:
break
print (x)
This will ask the user for a number again and again to be put in it until he quits
def collatz(x):
while x !=1:
print(int(x))
if x%2 == 0:
x = x/2
else:
x = 3*x+1
this is what i propose..
seq = []
x = (int(input("Add number:")))
if (x != 1):
print ("Number can't be 1")
while x > 1:
if x % 2 == 0:
x=x/2
else:
x = 3 * x + 1
seq.append (x)
print seq
This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.
collatz = []
def collatz_sequence(x):
while x != 1:
if x % 2 == 0:
x /= 2
else:
x = (3*x + 1)/2
collatz.append(int(x))
print(collatz)
collatz_sequence()
Recursion:
def collatz(n):
if n == 1: return [n]
elif n % 2 == 0: return [n] + collatz(int(n/2))
else: return [n] + collatz(n*3+1)
print(collatz(27))
steps=0
c0 = int(input("enter the value of c0="))
while c0>1:
if c0 % 2 ==0 :
c0 = c0/2
print(int(c0))
steps +=1
else:
c0 = (3 * c0) + 1
print(int(c0))
steps +=1
print("steps= ", steps)
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
def collatz_sequence(N):
seq = [N]
m = 0
maxN = 0
while seq[-1] > 1:
if N % 2 == 0:
k = N//2
seq.append(N//2)
if k > maxN:
maxN = k
else:
k = 3*N+1
seq.append(3*N+1)
if k > maxN:
maxN = k
N = seq[-1]
m = m + 1
print(seq)
x = np.arange(0, m+1)
y = np.array(seq)
xlim(0, m+1)
ylim(0, maxN*1.1)
step(x, y)
show()
def collatz_exec():
print('Enter an Integer')
N = int(input())
collatz_sequence(N)
This is how you can use it:
>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]
And a plot that shows the sequence:
seq = []
def collatz_sequence(x):
global seq
seq.append(x)
if x == 1:
return
if (x % 2) == 0:
collatz_sequence(x / 2)
else:
collatz_sequence((x * 3) + 1)
collatz_sequence(217)
print seq
def collataz(number):
while number > 1:
if number % 2 == 0 :
number = number //2
print(number)
elif number % 2 ==1 :
number = 3 * number + 1
print(number)
if number == 1 :
break
print('enter any number...!')
number=int(input())
collataz(number)

Categories