KnowledgeBoat Logo

Computer Science

Write a program to display all of the integers from 1 up to and including some integer entered by the user followed by a list of each number's prime factors. Numbers greater than 1 that only have a single prime factor will be marked as prime.

For example, if the user enters 10 then the output of the program should be:

Enter the maximum value to display: 10
1 = 1
2 = 2 (prime)
3 = 3 (prime)
4 = 2x2
5 = 5 (prime)
6 = 2x3
7 = 7 (prime)
8 = 2x2x2
9 = 3x3
10 = 2x5

Python

Python Control Flow

23 Likes

Answer

import math

n = int(input("Enter an integer: "))

for i in range(1, n + 1) :
    if i == 1:
        print("1 = 1")
    else :
        print(i, "=", end=' ')
        c = 0
        for j in range(1, i + 1) :
            if i % j == 0:
                c += 1
        if c == 2:
            print(i, "(prime)", end = '')
            print()
        else :
            t = i
            while t % 2 == 0 :
                print("2", end='x')
                t = t // 2
            k = 3
            x = math.ceil(math.sqrt(t)) + 1
            while k <= x :
                while (t % k == 0) :
                    print(k, end='x')
                    t = t // k
                k += 2

            if t > 2 :
                print(t, end='x')
                
            print()

Output

Enter an integer: 10
1 = 1
2 = 2 (prime)
3 = 3 (prime)
4 = 2x2x
5 = 5 (prime)
6 = 2x3x
7 = 7 (prime)
8 = 2x2x2x
9 = 3x3x
10 = 2x5x

Answered By

14 Likes


Related Questions