Question 3: Amicable
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
def abundant(n):
while n > 0:
a = n
k = n
y = 0
total = 0
while k > y or n == 0:
if n % k == 0:
y = n // k
if k != n:
total = total + k + y
if k == y:
total = total - y
k -=1
total = total + 1
print(total)
def abundant2(n):
b = n
x = n
y = 0
total2 = 0
while x > y or n == 0:
if n % x == 0:
y = n // x
if x != n:
total2 = total2 + x + y
if x == y:
total2 = total2 - y
x -=1
total2 = total2 + 1
print(total2)
if total == b and total2 == a:
print('Amicable!')
amicable_numbers2 = int(total2)
amicable_numbers = int(total)
else:
print('Nope')
return abundant2
n += 1
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
nums = [amicable_numbers2, amicable_numbers]
nums2 = [n for n in nums if n >= amicable_numbers2 and n <= amicable_numbers]
return nums2
# return a value that is less than amicable_numbers2 and less than amicable_numbers???
Related
Following is a factorization program in Python. It works fine till 102030405060708001 but produces incorrect results for greater integers. Why is this so?
import math
a = []
def prime(n):
isPrime = True
for r in range(2,int(n**(1/2)+1)):
if n%r == 0:
isPrime = False
return isPrime
def factor(number):
if prime(number):
a.append(int(number))
for r in range(2, 1 + int(number**(1/2))):
if number%r == 0:
a.append(r)
number = number/r
factor(number)
break
return a
number = int(input("Enter a number whose factors you want:"))
factor(number)
print(f"Factor of {number} are ", end = ": ")
print(*a, sep = ' X ')
print(math.prod(a))
Example
Factor of 102030405060708001 are : 1867601 X 54631800401.
And the product of these factors is 102030405060708001
Factor of 102030405060708002 are : 2 X 2 X 2 X 2 X 2 X 3 X 3 X 5 X 5 X 5 X 6133 X 462119341.
But the product of these factors is 102030405060708000
Factor of 102030405060708003 are : 3 X 2 X 2 X 2 X 2 X 2 X 3 X 5 X 5 X 5 X 6133 X 462119341.
But the product of these factors is 102030405060708000
Is there a way to list super primes (primes in a prime position wikipedia article) between 1 and n using NumPy.
I got this without Numpy, is that okay?
here is the code based on
Sieve of Atkin
import math
is_prime = list()
limit = 100
for i in range(5, limit):
is_prime.append(False)
for x in range(1, int(math.sqrt(limit)) + 1):
for y in range(1, int(math.sqrt(limit)) + 1):
n = 4 * x ** 2 + y ** 2
if n <= limit and (n % 12 == 1 or n % 12 == 5) and n <= len(is_prime):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3 * x ** 2 + y ** 2
if n <= limit and n % 12 == 7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3 * x ** 2 - y ** 2
if x > y and n <= limit and n % 12 == 11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5, int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n ** 2, limit + 1, n ** 2):
if k <= len(is_prime):
is_prime[k] = False
for n in range(5, limit):
if n < len(is_prime) and is_prime[n]:
print(n)
Numpy Code Version
Sieve modification of Numpy Sieve by user2357112 supports Monica
import numpy as np
def sieve(n):
'''
Sieve of Erastosenes using numpy
'''
flags = np.ones(n, dtype=bool) # Set all values to True
# Set 0, 1, and even numbers > 2 to False
flags[0] = flags[1] = False
flags[4:n:2] = False
for i in range(3, n, 2):
# Check for odd primes
if flags[i]:
flags[i*i::i] = False
return np.flatnonzero(flags) # Indexes of True are prime
def superPrimes(n):
'''
Find superprimes
'''
# Find primes up to n using sieve
p = sieve(n)
# p(i) denotes the ith prime number, the numbers in this sequence are those of the form p(p(i))
# Want to find numbers we can index in the list (i.e. has to be less than len(p))
indexes = p[p < len(p)] # base 1 indexes within range
return p[indexes-1] # Subtract 1 since primes array is base 0 indexed
Test
print(superPrimes(200))
# Output: [ 3 5 11 17 31 41 59 67 83 109 127 157 179 191]
i can't understand why the output of my code concatnates the digits instead of showing their sum:
#Get a number, and show the number of digits and the sum of the digits.
num = int(input('Enter a number: '))
j = 0
i = 1
k = 0
while i < num:
i = i*10
j += 1
k += (num - k)%i
print (f' The number has {j} digit(s), and the sum is: {k}')
Follow the code. Let's say num = 432:
i = 1 * 10 = 10
j = 0 + 1 = 1
k = 0 + (432 - 0)%10 = 2
---
i = 10 * 10 = 100
j = 1 + 1 = 2
k = 2 + (432 - 2)%100 = 2 + 32 = 34
---
i = 100 * 10 = 1000
j = 2 + 1 = 3
k = 34 + (432 - 34)%1000 = 34 + 398 = 432
This algorithm is most definitely not adding every digit. There are several ways to do what you intend in python. One way is inputting the number as a string and summing every digit casting them as integers inside a generator:
num = input('Enter a number: ')
total = sum(int(digit) for digit in num)
print(total)
If you want the number to be an integer since the beginning, you can also do this:
num = int(input('Enter a number: '))
total = 0
while num > 0:
digit = num%10
total += digit
num /= 10 # num //= 10 in python 3
print(total)
n = int(input('Enter n: '))
count = 1
sum = 0
number = 1
while (count <= n):
sum = sum + number
count = count + 1
number = number + 2
print('Sum =', sum)
Is it possible to use the same concept for 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 .... + n
You could use a list comprehension to make this more elegant and pythonic:
def sum_series(start, end):
return sum([i**2 for i in range(start, end+1)])
print(sum_series(1,10))
Output:
385
Or using higher order functions:
>>> sum(map(lambda x: x**2, range(1,11)))
385
Something like this should do
n = int(input('Enter n: '))
count = 1
sum = 0
while (count <= n):
sum = sum + count*count
print("{s}+".format(s=sum)
count = count + 1
print('Sum =', sum)
So I have this Collatz conjecture assignment. Basically I have to write a program to which I give number and it will calculate Collatz conjecture for it. Here is my problem though: the number that will come out will be written like this :
12
6
3
10
5
16
8
4
2
1
When they should be in list like this [12, 6, 3, 10, 5, 16, 8, 4, 2, 1].
And here is my code:
n = int(input("The number is: "))
while n != 1:
print(n)
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
print(1)
You have to store the numbers in a list
result = []
while n != 1:
result.append(n)
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
result.append(n)
print result
This is also an option. A silly one, but still:
n = int(input("The number is: "))
print('[', end='')
while n != 1:
print(n, end=', ')
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
print('1]')
A recursive version, just for fun:
number = int(input("the number is: "))
def collatz(n):
if n == 1:
return [n]
elif n % 2 == 0:
return [n] + collatz(n/2)
else:
return [n] + collatz((3*n)+1)
print collatz(number)