design an algorithm (expessed in pseudocode) for finding all the factors of the positive integer for example in the caseof the integer 12, your algorithm should report 1, 2, 3, 4, 6 and 12.
for i = 1 to n if n mod i = 0 print i end if end for
how do we do it using a while statement/ plz help
i = 1 while i <= n if n mod i = 0 print i end if i = i + 1 end while
In python I have this, which would likely work better for large numbers since it does not need to search through all numbers and only the root of the given value. import math def factors(x): l = [] for i in range(1,math.ceil(math.sqrt(x))): if x % i == 0: l.append(i) l.append(x//i) l.sort() return l
And the version with while def factors(x): l = [] i = 1 while i < math.ceil(math.sqrt(x)): if x % i == 0: l.append(i) l.append(x//i) i += 1 l.sort() return l
Dear msmithhnova, shouldn't "math.ceil(math.sqrt(x))" should be replaced by "x" in your code? Please note that the algorithm should display all the factors (not prime factors).
No, it only needs to search up to the root of x to get all factors then it adds i and x//i which gives it both factors, Here is the unsorted output of a few numbers. >>> factors(12) [1, 12, 2, 6, 3, 4] >>> factors(3750) [1, 3750, 2, 1875, 3, 1250, 5, 750, 6, 625, 10, 375, 15, 250, 25, 150, 30, 125, 50, 75] >>> factors(123456789) [1, 123456789, 3, 41152263, 9, 13717421, 3607, 34227, 3803, 32463, 10821, 11409] >>> factors(144000) [1, 144000, 2, 72000, 3, 48000, 4, 36000, 5, 28800, 6, 24000, 8, 18000, 9, 16000, 10, 14400, 12, 12000, 15, 9600, 16, 9000, 18, 8000, 20, 7200, 24, 6000, 25, 5760, 30, 4800, 32, 4500, 36, 4000, 40, 3600, 45, 3200, 48, 3000, 50, 2880, 60, 2400, 64, 2250, 72, 2000, 75, 1920, 80, 1800, 90, 1600, 96, 1500, 100, 1440, 120, 1200, 125, 1152, 128, 1125, 144, 1000, 150, 960, 160, 900, 180, 800, 192, 750, 200, 720, 225, 640, 240, 600, 250, 576, 288, 500, 300, 480, 320, 450, 360, 400, 375, 384]
oh... so, // stands for integer division!
Yes, basically that is correct. Python refers to it as floor division because something like 5.5//2.3 will give a result of 2.0
thank you.... very much i think am covered with all your sollutions
Join our real-time social learning platform and learn together with your friends!