a=10,b=20,c=3
for example I need program to find how many multiples do c=3 have that are between a,b or b,a? how to make that program without using loop? in this example with this input program must give us output 3 because 3's multiples are 12,15,18 and these numbers are in between 10,20 so 3 will be correct.
CodePudding user response:
use range
starting from the nearest upper (or equal) divider:
import math
len(range(math.ceil(a/c)*c, b, c)) # if the upper bound is inclusive, use b 1
output: 3
for a=10;b=20;c=3
NB. you can also get directly the number using (b-math.ceil(a/c)*c)//c 1
(both bounds included)
NB. if you do not want to use the math
module: (b (-a//c)*c)//c 1
CodePudding user response:
You can take the quotient of both the numbers divided by c and then subtract them to get the number of multiple between them
a=100
b=200
c=3
multiple1 = a//c
multiple2 = b//c
print(multiple2-multiple1)
# this is not required, just for confirming that above logic works
count = 0
for i in range(a,b):
if(i%c == 0):
count =1
print(count)
both outputs are 33
CodePudding user response:
I have written the code below:
def count_multiples(a, b, c):
count = 1 if min(a, b)%c == 0 else 0
count = abs(a//c - b//c)
return count
print(count_multiples(30, 15, 2))
This takes into account both the lower and upper bounds.
I have tested it for limited number of testcases but it should work for any combination of numbers. You can try this and let me know if it works.
CodePudding user response:
You will need the "numpy" package for this. If you have not installed it yet, open your terminal and run "conda install numpy" or "pip install numpy"
The code:
Import numpy as np
a=10
b=20
c=3
x=np.arange(a,b,1) #it will create a list with integers [10,11,...,18,19]
# if you want to include/exclude 10,20 do /- 1
count_multiples = list(map(lambda y: y %c, x)).count(0)
# y %c, will give the modulo. The modulo will be 0, if the integer is a multiple of c
# .count(0), will count how many modulos are zero
# with lambda you create a function, in this case y %c
# map can be used instead of a loop and will check every element of the list
CodePudding user response:
a,b,c=10,20,5
def countmultiples(a,b,c):
start = a-a%c
multiples = list(range(start,b 1,c))
sumofmultiples = len(multiples)
if multiples[0]%c!=0 or multiples[0]<a:
sumofmultiples-=1
multiples.pop(0)
return multiples,sumofmultiples
print(countmultiples(a,b,c)
so i needed to find multiples of between a and b, also both included. that way it works perfectly for every number without loop,recursive and built-in fuctions.