0

I have to write a code to get 10 numbers at input. Then, find the number with higher number of prime factors. If two number have the same amount of prime factor, then print the bigger one.

For instance, for sample input of : input values:

123
43
54
12
76
84
98
678
543
231

the Output values should be like this:

678 3

Here is my code, however the output is not correct:

import math

# Below function will print the
# all prime factor of given number
def prime_factors(num):
    # Using the while loop, we will print the number of two's that divide n
    added1 = 0
    added2 = 0
    while num % 2 == 0:
        added1 = 1
        print(2, )
        num = num / 2

    for i in range(3, int(math.sqrt(num)) + 1, 2):
        # while i divides n , print i ad divide n
        while num % i == 0:
            added2 = 1
            print(i, )
            added2 += 1
            num = num / i
    if num > 2:
        print(num)

    added = added1 + added2
    print(added)
    return added
    # calling function


input_numbers = []
for i in range(0,10):
    input_numbers.append(int(input()))

contest = 1
for item in input_numbers:
    if prime_factors(item) > contest:
        contest += 1
        contest2 = item


print(contest2)
Majid
  • 421
  • 6
  • 19
  • Explain "not working correctly": Edit the question to show a sample input, expected and real output for the input. – Michael Butscher Feb 19 '22 at 21:32
  • Having added2=1 followed by a added2+=1 does not make any sense. Similarly just added1=1 in the first loop. Why is there a first while loop anyway, why not have one counter "primeFactors" that is properly named and behaves as desired? – luk2302 Feb 19 '22 at 21:34

1 Answers1

1

Using an algorithm from this answer I wrote one to solve your problem.

def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors

input_numbers = []
for i in range(0,10):
    input_numbers.append(int(input()))

highest_num = 0
highest_amount = 1
for num in input_numbers:
    factors = list(dict.fromkeys(prime_factors(num)))
    factors_amount = len(factors)
    if factors_amount > highest_amount:
        highest_num = num
        highest_amount = factors_amount
    elif factors_amount == highest_amount:
        if num > highest_num:
            highest_num = num

print(highest_num,highest_amount)
emetsipe
  • 162
  • 1
  • 9