Factors of an integer: Difference between revisions
no edit summary
m (→{{Header|Haskell}}: `bool` in lieu of `if then else`) |
No edit summary |
||
Line 182:
+64: 1, 64, 2, 32, 4, 16, 8
</pre>
=={{header|ALGOL-M}}==
Instead of displaying 1 and the number itself as factors, prime numbers are explicitly reported as such. To reduce the number of test divisions, only odd divisors are tested if an initial check shows the number to be factored is not even. The upper limit of divisors is set at N/2 or N/3, depending on whether N is even or odd, and is continuously reduced to N divided by the next potential divisor until the first factor is found. For a prime number this will be the square root of N, which avoids the necessity of explicitly calculating that value. (ALGOL-M does not have a built-in square root function.)
<lang algol>
BEGIN
COMMENT ALGOL-M PROGRAM TO DISPLAY THE FACTORS OF AN INTEGER
INTEGER I, N, LIMIT, FOUND, START, DELTA;
STRING(1) ANOTHER;
COMMENT COMPUTE P MOD Q;
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT MAIN PROGRAM BEGINS HERE;
ANOTHER := "Y";
WHILE ANOTHER = "Y" OR ANOTHER = "y" DO
BEGIN
WRITE ("Number to factor:");
READ (N);
WRITE ("The factors are:");
COMMENT CHECK WHETHER NUMBER IS EVEN OR ODD;
IF MOD(N, 2) = 0 THEN
BEGIN
START := 2;
DELTA := 1;
END
ELSE
BEGIN
START := 3;
DELTA := 2;
END;
COMMENT TEST POTENTIAL DIVISORS;
FOUND := 0;
I := START;
LIMIT := N / START;
WHILE I <= LIMIT DO
BEGIN
IF MOD(N, I) = 0 THEN
BEGIN
WRITE (I);
FOUND := FOUND + 1;
END;
I := I + DELTA;
IF FOUND = 0 THEN LIMIT := N / I;
END;
IF FOUND = 0 THEN WRITE ("None - the number is prime.");
WRITE(" ");
WRITE("Do another (y/n)?");
READ (ANOTHER);
END;
WRITE (" ");
WRITE ("Goodbye");
END
</lang>
=={{header|ALGOL W}}==
|