That is yet another unfulfilled task dating from my Primary School. I was embarking on the challenge to write a program in DBASE to find all the factors of a number using heuristic like 'If the sum of digits of a number is divisible by 3, then the number itself is divisible by 3', or 'If the last digit of a number is 0 or 5, then it is divisible by 5'... etc. However, what I haven't fully considered is any number except prime number would always contain repeated factor, i.e. 2^n, 3^n...etc; and I fail to find a way to do recursion in DBASE so I gave up. Instead I write an extremely simple program which use the modulus of a number by a divisor, when there is a remainder then it return false otherwise true.
Now, I finally have the momentum to pick up when I left, to devise a method to find all divisor, include repeated ones. (Actually it is intended to find all the prime numbers within a range.)
Input the number X,
Initialize an array with length square of X.
The test would be ranged from 2 to square of X,
'Starting from 2 to N,
test if X is divisble by that number, if so added 1 to position (that number) of an array,
continue the process until it is no longer divisble by that number;'
The answer is those array element with value great than 0.
(We can branch off at divisibility test using any given criteria. )
i.e. If array(2)=3, then 2,4,8 is all factor of the number.
To use this method to find all prime number, we only require those with the result which all value of array is zero.
Fun to try!
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言