Code archives/Algorithms/Factor Calculator

This code has been declared by its author to be Public Domain code.

Download source code

Factor Calculator by schilcote2008
This function calculates the factors of any number you pass to it. It then stores the numbers in a memory bank (I think, I've had it so long I've forgotten how to use it) whick you peekint (is that in B+?) or equivalent to retrive.
Global FCBnk
Function factor (Num)
DebugLog"Factor calculating function called"
FCBnk=CreateBank (1024)
Fact2=1
Repeat
Rep=Rep+1
Fact=Fact+1
;Detect need for change in second number
If Fact=num Then
Fact2=Fact2+1
Fact=1
EndIf
DebugLog "Checking For Factor, "+Fact+" * "+Fact2
;Detect factor
Test=Fact*Fact2
If Test=Num Then 
PokeInt FCBnk,Ofst,Fact
DebugLog "Factor Calculated,"+Fact
ofst=ofst+3
EndIf
Until (Test=Num And Fact=1)
DebugLog"Factor of 1 reached, end computation."
End Function

Comments

Dabhand2008
Nice... I'll give this 10/10 since the author stated 'I think, but I've forgotten' in the description! ;)

Never seen that one before! :D

Dabz


schilcote2008
Really? It took me 30 seconds to make. The factor calculator program is alot better. I updated that one a few times, and never really paid attention to this. If anyone asks I can throw the program at them. Maybe it's engine can be used for something else. Like a function.


Matty2009
Your original code will not work for the following reasons, and could be written better:
1. variable Rep <- never referenced aside from incrementing by 1 each iteration
2. Bank is only 1024 bytes long, so you are limited to having a rather limited number of factors, and wasting memory (albeit not much) if it is not used
3. You are incrementing the offset in the bank by 3 bytes, thus overwriting the last byte of each integer which is 'poked'.

A simpler, perhaps more elegant method, would be to do as follows:

It could be made smarter, such as using a variable data size 1 byte for factors<256, 2bytes for factors<65536 else 4 bytes
Function GetFactors(Num)
if Num = 0 then return 
bank=createbank() ; no size initially, we will resize it as we fill it
offset=0
for factor = 1 to Num
	if Num Mod Factor = 0 then 
		ResizeBank(bank,banksize(bank)+4)
		PokeInt bank,offset,factor
		offset=offset + 4 ;size of integer 	
	endif 	
next
return bank ;no need for a global bank as we will return it here and the user can then do what they want with it.
End Function 



Code Archives Forum