Factors of an integer: Difference between revisions
Content added Content deleted
No edit summary |
(added BASIC) |
||
Line 32: | Line 32: | ||
1,53 |
1,53 |
||
1,2,4,8,16,32,64</pre> |
1,2,4,8,16,32,64</pre> |
||
=={{header|BASIC}}== |
|||
{{works with|QBasic}} |
|||
This example stores the factors in a shared array (with the original number as the last element) for later retrieval. |
|||
Note that this will error out if you pass 32767 (or higher). |
|||
<lang qbasic>DECLARE SUB factor (what AS INTEGER) |
|||
REDIM SHARED factors(0) AS INTEGER |
|||
DIM i AS INTEGER, L AS INTEGER |
|||
INPUT "Gimme a number"; i |
|||
factor i |
|||
PRINT factors(0); |
|||
FOR L = 1 TO UBOUND(factors) |
|||
PRINT ","; factors(L); |
|||
NEXT |
|||
PRINT |
|||
SUB factor (what AS INTEGER) |
|||
DIM tmpint1 AS INTEGER |
|||
DIM L0 AS INTEGER, L1 AS INTEGER |
|||
REDIM tmp(0) AS INTEGER |
|||
REDIM factors(0) AS INTEGER |
|||
factors(0) = 1 |
|||
FOR L0 = 2 TO what |
|||
IF (0 = (what MOD L0)) THEN |
|||
'all this REDIMing and copying can be replaced with: |
|||
'REDIM PRESERVE factors(UBOUND(factors)+1) |
|||
'in languages that support the PRESERVE keyword |
|||
REDIM tmp(UBOUND(factors)) AS INTEGER |
|||
FOR L1 = 0 TO UBOUND(factors) |
|||
tmp(L1) = factors(L1) |
|||
NEXT |
|||
REDIM factors(UBOUND(factors) + 1) |
|||
FOR L1 = 0 TO UBOUND(factors) - 1 |
|||
factors(L1) = tmp(L1) |
|||
NEXT |
|||
factors(UBOUND(factors)) = L0 |
|||
END IF |
|||
NEXT |
|||
END SUB</lang> |
|||
Sample outputs: |
|||
Gimme a number? 17 |
|||
1 , 17 |
|||
Gimme a number? 12345 |
|||
1 , 3 , 5 , 15 , 823 , 2469 , 4115 , 12345 |
|||
Gimme a number? 32765 |
|||
1 , 5 , 6553 , 32765 |
|||
Gimme a number? 32766 |
|||
1 , 2 , 3 , 6 , 43 , 86 , 127 , 129 , 254 , 258 , 381 , 762 , 5461 , 10922 , |
|||
16383 , 32766 |
|||
=={{header|C}}== |
=={{header|C}}== |