Im currently in college and I have an assignment that involves multiplying the primes and non primes below 45, so that their product doesn't go over 45. The language is python and I have tried doing for loops and checking for prime and not prime with modulus but I don't know where to go from there. (can't utilize arrays or anything related only loops, while else, elif etc.)
for num in range (1, 45):
if num > 1:
for num2 in range(2, 45):
if (num%num2) == 0:
n = num2
print(n, 'is Prime')
if num * num2 < 45:
print('Number ', num, '*', num2, '=', num*num2)
What exactly im trying to achieve is to first find all the prime numbers, then multiply them by all the non primes. Those primes and non primes are in the range of 1 - 45. Then, I Have to multiply them and their product has to be less than 45 then print that.
UPDATE: So I tried Thanh Tùng Nguyễn's program which is very well built, but I Can't utilize functions since I haven't been taught that (aka would be weird), what I tried to do is simply take what the function is and tried to just implement it into the loops themselves setting n as a boolean value, but my print doesn't amount to anything and I can't catch what's happening. The terminal just stays completely empty. My guess is on the last 'if not' statement, where I have probably written it wrong because I can't understand it myself why it isn't working when im treating it the same as a function through the entire block.
Here's what I got:
from math import sqrt
for num1 in range (2, 46):
if num1 <= 1:
n = False
for i in range (2, int(sqrt(num1))):
if num1%i == 0:
n = False
n = True
if n == True:
for num2 in range (1, 46):
if num2 <= 1:
n = False
for j in range (2, int(sqrt(num2))):
if num2%j == 0:
n = False
n = True
if not n == True:
if num1 * num2 < 45:
print(num1, '*', num2, '=', num1*num2)
You could create a prime-number check function like this:
from math import sqrt
def checkPrime(num):
if num <= 1:
return False
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
return False
return True
Note that you can just check from 2 to √n to optimize it. From there, just find all prime numbers below 45 and multiply it with a non-prime number:
from math import sqrt
def checkPrime(num):
if num <= 1:
return False
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
return False
return True
for n in range(2, 45+1):
if checkPrime(n):
for j in range(1, 45+1):
if not checkPrime(j):
if n * j < 45:
print(n, " * ", j, " = ", n*j)
Output:
2 * 1 = 2
2 * 4 = 8
2 * 6 = 12
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
2 * 12 = 24
2 * 14 = 28
2 * 15 = 30
2 * 16 = 32
2 * 18 = 36
2 * 20 = 40
2 * 21 = 42
2 * 22 = 44
3 * 1 = 3
3 * 4 = 12
3 * 6 = 18
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
3 * 12 = 36
3 * 14 = 42
5 * 1 = 5
5 * 4 = 20
5 * 6 = 30
5 * 8 = 40
7 * 1 = 7
7 * 4 = 28
7 * 6 = 42
11 * 1 = 11
11 * 4 = 44
13 * 1 = 13
17 * 1 = 17
19 * 1 = 19
23 * 1 = 23
29 * 1 = 29
31 * 1 = 31
37 * 1 = 37
41 * 1 = 41
43 * 1 = 43
If I understand correctly, you need to multiply primes with non-primes. This means that the products will be formed of 3 or more primes.
To have 3 primes in the product, you can have 2 at most 5 times. You can have 3 at most 3 times, 5 at most twice, 7/11 no more than once.
So you only need to take into account 2, 3, 5, 7 and 11 as primes and combine them in sets of 3 or more without going over 45:
You could nest 5 for-loops for the number of 2s, 3s, 5s, 7s and 11s in the product.
For example:
for p2 in range(7):
for p3 in range(4):
for p5 in range(3):
for p7 in range(2):
for p11 in range(2):
prod = 2**p2 * 3**p3 * 5**p5 * 7**p7 * 11**p11
if prod > 45 : continue
if p2+p3+p5+p7+p11 < 3: continue
if p2: print(2,'x',prod//2,'=',prod)
if p3: print(3,'x',prod//3,'=',prod)
if p5: print(5,'x',prod//5,'=',prod)
if p7: print(7,'x',prod//7,'=',prod)
if p11: print(11,'x',prod//11,'=',prod)
Output:
3 x 15 = 45
5 x 9 = 45
3 x 9 = 27
2 x 21 = 42
3 x 14 = 42
7 x 6 = 42
2 x 15 = 30
3 x 10 = 30
5 x 6 = 30
2 x 9 = 18
3 x 6 = 18
2 x 22 = 44
11 x 4 = 44
2 x 14 = 28
7 x 4 = 28
2 x 10 = 20
5 x 4 = 20
2 x 6 = 12
3 x 4 = 12
2 x 18 = 36
3 x 12 = 36
2 x 4 = 8
2 x 20 = 40
5 x 8 = 40
2 x 12 = 24
3 x 8 = 24
2 x 8 = 16
2 x 16 = 32à
You can also do it the other way around, by counting the primes that form each number up to 45 and, if there are 3 or more primes, print the ones that are part of the number as you go:
for prod in range(8,46):
primeCount = 0
rest = prod
for prime in range(2,12):
while rest and rest % prime == 0:
primeCount += 1
rest = rest//prime
if primeCount<3: continue
if prod%2==0: print(prod,'=',2,'x',prod//2)
if prod%3==0: print(prod,'=',3,'x',prod//3)
if prod%5==0: print(prod,'=',5,'x',prod//5)
if prod%7==0: print(prod,'=',7,'x',prod//7)
if prod%11==0: print(prod,'=',11,'x',prod//11)
Note that, even though I'm dividing by non=primes in the counting loop, only primes will actually be counted because, as the rest is reduced, multiples of previous primes will no longer divide the rest evenly.
Output:
8 = 2 x 4
12 = 2 x 6
12 = 3 x 4
16 = 2 x 8
18 = 2 x 9
18 = 3 x 6
20 = 2 x 10
20 = 5 x 4
24 = 2 x 12
24 = 3 x 8
27 = 3 x 9
28 = 2 x 14
28 = 7 x 4
30 = 2 x 15
30 = 3 x 10
30 = 5 x 6
32 = 2 x 16
36 = 2 x 18
36 = 3 x 12
40 = 2 x 20
40 = 5 x 8
42 = 2 x 21
42 = 3 x 14
42 = 7 x 6
44 = 2 x 22
44 = 11 x 4
45 = 3 x 15
45 = 5 x 9
Related
Junior Python Coder here! Trying to print multiplication table with user input but stuck.
min_num=1
max_num=11
starting_range = int(input ("Enter the minimum number: "))
ending_range = int(input ("Enter the maximum number: "))
print ("The Multiplication Table of: ", starting_range)
for count in range(1, 11):
print (starting_range, 'x', count, '=', ending_range * count)
if max_num - min_num > 10 :
print('invalid range ')
else:
for num in range (min_num,max_num):
print ("The Multiplication Table of: ", ending_range)
for count in range(min_num, max_num):
print (starting_range, 'x', count, '=', ending_range * count)
I'm not sure I really understand what you're trying to do as your code isn't formatted, but for a multiplication table, a nested loop is a solution.
The basic idea is: For every number in the given range, loop over the whole range and multiply it by each element. This will print the whole multiplication table.
start = 1 # You can change these to be inputted by the user.
end = 10
for i in range(start, end + 1): # We add 1 to the end because range() is exclusive on endpoint.
for j in range(start, end + 1):
print(f"{i} x {j} = {i * j}")
If you only need the table as something like:
15 x 1
15 x 2
15 x 3
...
You can do this with one loop:
num = 10
for i in range(1, num + 1):
print(f"{num} x {i} = {num * i}")
I recommend you search up on F-strings in Python if you do not understand the print(f"..") parts. They're very convenient. Good luck!
Minimal change to original code:
min_num = 1
max_num = 11
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
# Removed the error checking, wasn't sure precisely what it was meant to do.
for num in range(starting_range,ending_range):
print ("The Multiplication Table of: ", num)
for count in range(min_num, max_num):
print (num, 'x', count, '=', num * count)
Try it at https://www.mycompiler.io/view/7JVNtxkT53k
This prints:
The Multiplication Table of: 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
The Multiplication Table of: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The Multiplication Table of: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Alternative code defining a function:
def print_multiplication_table(n, max_value=11):
if n > max_value or n <= 0:
raise ValueError
print(f"The Multiplication Table of: {n}")
for m in range(1, max_value):
print(f"{n} x {m} = {n*m}")
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
for i in range(starting_range, ending_range):
print_multiplication_table(i)
Try it at https://www.mycompiler.io/view/1uttFLmFEiD
Code
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a+1):
print(i)
for j in range(1, b + 1):
c = i * j
print(i, "*", j, "=", c)
Desired output
1 2 3
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30
You can tell print to finish with something other than a newline by specifying the "end" argument:
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end=" ")
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end=" ")
print("")
In this case I split the main loop into two separate loops, the first outputs the top line (1, 2, 3...) with some large spacing, whilst the second then does all of the others with slightly less spacing.
I also switched the order of the later loops since there should be b lines, each with a multiplications, so the b loop needs to be the outer (first) loop.
In both cases an empty print statement is used to output a newline when we need it.
This is what you are looking for:
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a + 1):
print(i, end="\t"*4)
print("")
for k in range(1, b + 1):
for j in range(1, a + 1):
print(j, "*", k, "=", j*k, end="\t"*2)
print("")
You have to think line-by-line, since you cannot go back in stdout.
The first for will fill the first line
I modified your nested loop because you were using the wrong variables
"\t" is meant to get decent formatting, but it will eventually break if numbers are too big: I believe there is a more refined approach that I am not aware of
print("") is just meant to go to the next line
Approach
Approach is use f-strings to left align all the prints into fields of width 20
Use fixed field widths since otherwise columns won't line up with single and multi-digit numbers
Use print parameter end = '' to avoid carriage returns on after printing a field
Code
a = int(input("enter a no "))
b = int(input("enter a range "))
width = 20
for i in range(1, a+1):
print(f'{i:<{width}}', end="") # Print all multipliers on a single row
print("")
for j in range(1, b + 1):
# Looping over multiplication row
for i in range(1, a+1): # Looping through the columns to multipl
s = f'{i} * {j} = {i*j}' # Expression for column field
print(f'{s:<{width}}', end = '') # Print field left aligned to width 20
print("") # New row
Test
enter a no 4
enter a range 10
1 2 3 4
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 4 * 1 = 4
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 4 * 3 = 12
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 4 * 10 = 40
I corrected it like this. Thankyou guys.
just add the end="\t"*4 to fix the alignment issue.
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end="\t"*4)
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end="\t"*2)
print("")
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
x = 1
y = 1
while x <= 10 and y <= 12:
f = x * y
print(f)
y = y + 1
x = x + 1
tablesOneToTen()
I am trying to make a function that will give me values from the multiplication table from 1-10.
Should I add if and elif statements in addition to nested while loops to make this code work?
For these sort of iteration tasks you're better off using the for loop since you already know the boundaries you're working with, also Python makes creating for loops especially easy.
With while loops you have to check that you are in range using conditionals while also explicitly incrementing your counters making mistakes all the more likely.
Since you know you need multiplication tables for values of x and y ranging from 1-10 you can, to get you familiar with loops, create two for loops:
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
# This will iterate with values for x in the range [1-10]
for x in range(1, 11):
# Print the value of x for reference
print("Table for {} * (1 - 10)".format(x))
# iterate for values of y in a range [1-10]
for y in range(1, 11):
# Print the result of the multiplication
print(x * y, end=" ")
# Print a new Line.
print()
Running this will give you the tables you need:
Table for 1 * (1 - 10)
1 2 3 4 5 6 7 8 9 10
Table for 2 * (1 - 10)
2 4 6 8 10 12 14 16 18 20
Table for 3 * (1 - 10)
3 6 9 12 15 18 21 24 27 30
With a while loop, the logic is similar but of course just more verbose than it need to since you must initialize, evaluate the condition and increment.
As a testament to its uglyness, the while loop would look something like this:
def tablesOneToTen():
# initialize x counter
x = 1
# first condition
while x <= 10:
# print reference message
print("Table for {} * [1-10]".format(x))
# initialize y counter
y = 1
# second condition
while y <=10:
# print values
print(x*y, end=" ")
# increment y
y += 1
# print a new line
print(" ")
# increment x
x += 1
Using Python 3
for i in range(1, 10+1):
for j in range(i, (i*10)+1):
if (j % i == 0):
print(j, end="\t")
print()
or:
for i in range(1, 10+1):
for j in range(i, (i*10)+1, i):
print(j, end="\t")
print()
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Hope it would help you to get 1 to 10 table.
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(*("{:3}" .format (i*col) for col in a))
print()
I have this code:
def floyd(n):
count = 1
string = ""
for i in range(1,n+2):
for j in range(1,i):
string = string + " " + str(count)
count = count + 1
print(string)
string = ""
print floyd(6)
It prints:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
But I want it to look like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Will you help me figure out how to do so?
Python strings actually have a built-in center() method that can do that for you.
print(string.center(total_width))
You can set up total_width in advance with:
total_width = -1
for i in xrange(0, n):
total_width += 1 + len(str((n + n * n) / 2 - i))
Or
total_width = sum(1 + len(str((n + n * n) / 2 - i)) for i in xrange(0, n)) - 1
That is, the sum of the lengths of the string representations of the numbers in the same row as the nth triangle number (n² + n) ÷ 2.
Here’s a demo!
Using n you can find the last row first, the last number is (n**2 + n)/2, so the first number on last line is ((n**2 + n)/2) - (n-1), now last row is can be created using str.join and a list comprehension:
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
Now we can use the width of this line in string formatting to center other lines properly.
Code:
from itertools import count
def floyd(n):
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
width = len(last_row)
c = count(1)
for x in xrange(1, n):
line = ' '.join(str(next(c)) for _ in xrange(x))
print "{:^{}}".format(line, width)
print last_row
Demo:
>>> floyd(6)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
>>> floyd(8)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
def FloydT(n):
num=0
row=""
for i in range(1,n+1):
for j in range(1,i+1):
num+=1
row+=str(num)+" "
print(str.center(row,3*n)) # this line will do what you want
row=""
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to change a integer to string then back to integer due to it repeats till 100. For example, I have a multiple number and thefive number, it need's to do the sum then output it like print(multnum+"x5="+answer) in order to do that I must convert it to a string. This process repeats using while function so in order to do another sum using the multnum it must go back to a integer.
def output100_5table():
answer = 0
thefive = 5
multnum = 0
addmult = multnum+1
thetimes = "x5="
while answer < 100:
addmult = int(multnum+1)
answer = addmult*thefive
addmult = str(addmult)
answer = str(answer)
print(addmult+thetimes+answer)
output100_5table()
Is this what you are looking for? It was difficult to figure out what the code's purpose was.
>>> def show_table(multiplicand, product_limit):
multiplier = 1
while True:
product = multiplicand * multiplier
if product > product_limit:
break
print(multiplicand, 'x', multiplier, '=', product)
multiplier += 1
>>> show_table(5, 100)
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 x 11 = 55
5 x 12 = 60
5 x 13 = 65
5 x 14 = 70
5 x 15 = 75
5 x 16 = 80
5 x 17 = 85
5 x 18 = 90
5 x 19 = 95
5 x 20 = 100
>>> def show_table(multiplicand, product_limit):
for multiplier in range(1, product_limit // multiplicand + 1):
print(multiplicand, 'x', multiplier, '=', multiplicand * multiplier)
>>> show_table(5, 100)
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 x 11 = 55
5 x 12 = 60
5 x 13 = 65
5 x 14 = 70
5 x 15 = 75
5 x 16 = 80
5 x 17 = 85
5 x 18 = 90
5 x 19 = 95
5 x 20 = 100
>>>