exponential form to normal form in pascal - pascal

I'm having the following program:
var
N, M, Result: Real;
begin
Readln(N);
Readln(M);
if (N > 0) and (M > 0) then
Result := N / M;
Writeln(Result:10);
Readln();
end.
and I want the result to be in a normal form, not the exponential form (for example, 8.29 instead of 8.29E+000)

Try this:
Writeln (Result:10:2);
The 2 means "2 decimal places."
http://wiki.freepascal.org/Formatting_output

Use the format specifiers of Writeln, like
Writeln(Result:10:2), for 2 decimal digits.
Besides, your result variable will be undefined if N or M are <0. It's better to initialize it, e.g. to 0.

Related

how to check if the sum of digits is divisible by this sum?

I want to calculate the sum of the digits of a user-specified number first. Then I want to check if this number is divisible by the sum of its digits. Unfortunately, for example, for 21 it shows that it is not divisible, and for 200 that it is divisible. Maybe someone helps me. I'm just learning the language pl SQL.
DECLARE
n number(5):=&give_number;
temp_sum INTEGER;
r INTEGER;
a varchar(20);
BEGIN
temp_sum := 0;
WHILE n <> 0 LOOP
r := MOD(n, 10);
temp_sum := temp_sum + r;
n := Trunc(n / 10);
END LOOP;
a:=mod(r,temp_sum);
if a = 0 then
dbms_output.put_line('Divisible');
else
dbms_output.put_line('No divisible');
end if;
END;
You are checking if r is divisible by temp_sum and, if you consider what values they are holding then r is the most-significant digit and temp_sum is the digit sum. Which for an input of 21 checks whether 2 (the most-significant digit) is exactly divisible by 3, which it correctly reports that it is not divisible.
To fix it, you want to keep the input number in a variable that you do not modify and use that in the final comparison and not r:
If we remove some of the unnecessary variables and give the others more meaningful names:
DECLARE
input_value NUMBER(5) := &give_number;
remainder_value NUMBER(5) := input_value;
digit_sum INTEGER;
BEGIN
digit_sum := 0;
WHILE remainder_value <> 0 LOOP
digit_sum := digit_sum + MOD(remainder_value, 10);
remainder_value := TRUNC(remainder_value / 10);
END LOOP;
dbms_output.Put_line(remainder_value);
dbms_output.Put_line('sum of digits = ' || digit_sum);
IF MOD(input_value,digit_sum) = 0 then
dbms_output.put_line('Divisible');
ELSE
dbms_output.put_line('Not divisible');
END IF;
END;
/
Then when you put in 21 the output is:
0
sum of digits = 3
Divisible
And for 202, the output is:
0
sum of digits = 4
Not Divisible
db<>fiddle here
Here is a more compact way to write your PL/SQL block, using some of the features specific to the language. Perhaps the most interesting one is the nesting of program units (subroutines) - something that, in C for example, is not permitted. I am referring to the declaration and full code of a "helper function" (the sum of digits function) right in the DECLARE section of the outer block.
The function also demonstrates a compact way to write the function recursively. In this case recursion isn't too deep (only as many recursive calls as there are digits in the input number); in general, if you can write the same function using a loop, as you did, instead of using recursion, is preferred - far less overhead. On the other hand, with the proper settings (an advanced topic), the interpreter will inline the recursive calls - essentially converting the recursive function to a simple loop. That way you can have the best of both worlds: clean, compact code, yet efficient interpreted code and execution.
I also show the more compact way to display your output to the screen. You only need one call to put_line; let the "if" (or "case expression") take care of what is to be displayed within the put_line call. Moreover, the common part, 'Divisible', can be factored out; the case expression simply adds 'Not ' when it's needed.
declare
n number := &input_number;
function sum_of_digits(n integer) return integer is
begin
return mod(n, 10) + case when n < 10 then 0
else sum_of_digits(trunc(n/10)) end;
end;
begin
dbms_output.put_line(
case when mod(n, sum_of_digits(n)) != 0 then 'Not' end || 'Divisible');
end;
/
Notice one more thing: the outer block has a variable called n, but the function (in the declare section) also has a variable n. For the duration of the nested block (the function definition), n means the local variable. You need to always pay attention to such "masking" of an outer variable by a local variable by the same name.

Modulo of negative integers in Go

I am learning Go and I come from a Python background.
Recently, I stumbled onto a behaviour of the %(modulo) operator which is different from the corresponding operator in Python. Quite contrary to the definition of modular operation and remainder, the modulus of negative integers by a positive integer returns a negative value.
Example:
Python
a, b, n = -5, 5, 3
for i in range(a, b):
print(i%n)
Output:
1
2
0
1
2
0
1
2
0
1
Go
a, b, n := -5, 5, 3
for i:=a; i<b; i++ {
fmt.Println(i%n)
}
Output:
-2
-1
0
-2
-1
0
1
2
0
1
After reading about the Modulo operator and few similar questions asked about the reason behind these differences, I understand that these were due to design goals of the concerned languages.
Is there a built-in functionality in Go which replicates the modulus operation of Python?
Alternate: Is there an internal method for computing the "modulus" instead of the "remainder"?
See this comment by one of the language designers:
There are a several reasons for the current definition:
the current semantics for % is directly available as a result from x86 architectures
it would be confusing to change the meaning of the elementary operator % and not change its name
it's fairly easy to compute another modulus from the % result
Note that % computes the "remainder" as opposed to the "modulus".
There is not an operator or function in the standard library which replicates the modulus operation of Python.
It is possible to write a function which replicates the modulus operation of Python:
func modLikePython(d, m int) int {
var res int = d % m
if ((res < 0 && m > 0) || (res > 0 && m < 0)) {
return res + m
}
return res
}
Note that in Python 5 % -3 is -1 and this code replicates that behavior as well. If you don't want that, remove the second part after || in the if statement.
Is there an internal method for computing the "modulus" instead of the "remainder"?
Note that % computes the "remainder" as opposed to the "modulus".
These quotes are a bit misleading.
Look up any definition of "modulo", by and large it will say that it is the remainder after division. The problem is that when we say "the remainder", it implies that there is only one. When negative numbers are involved, there can be more than one distinct remainder. On the Wikipedia page for Remainder, it differentiates between the least positive remainder and the least absolute remainder. You could also add a least negative remainder (least negative meaning negative, but closest to 0).
Generally for modulus operators, if it returned a positive value, it was the least positive remainder and if it returned a negative value, it was the least negative remainder. The sign of the returned value can be determined in multiple ways. For example given c = a mod b, you could define the sign of c to be
The sign of a (what % does in Go)
The sign of b (what % does in Python)
Non-negative always
Here's a list of programming languages and their modulo implementations defined in this way https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages
Here's a branchless way to replicate Python's % operator with a Go function
func mod(a, b int) int {
return (a % b + b) % b
}
To reiterate, this follows the rule:
given c = a mod b, the sign of c will be the sign of b.
Or in other words, the modulus result has the same sign as the divisor
math/big does Euclidean modulus:
package main
import "math/big"
func mod(x, y int64) int64 {
bx, by := big.NewInt(x), big.NewInt(y)
return new(big.Int).Mod(bx, by).Int64()
}
func main() {
z := mod(-5, 3)
println(z == 1)
}
https://golang.org/pkg/math/big#Int.Mod
On Q2, you could use:
func modNeg(v, m int) int {
return (v%m + m) % m
}
Would output:
modNeg(-1, 5) => 4
modNeg(-2, 3) => 0
In most cases, just add the second number to the result:
Python:
-8%6 => 4
Golang:
-8%6 + 6 => 4
So the function will be like this:
func PyMod(d int, m int) int {
d %= m
if d < 0 {
d += m
}
return d
}
It works for some other situations such as a%-b in addition to -a%b.
But if you want it to work even for -a%-b, do like this:
func PyMod(d int, m int) int {
// Add this condition at the top
if d < 0 && m < 0 {
return d % m
}
d %= m
if d < 0 {
d += m
}
return d
}

Random number concentrated within a certain range

I wrote Fortran code to generate a series of random numbers. In this code, I could set up random number window (minimum and maximum random number) and percentage of random numbers within this window (number of random numbers). I want that the generated random numbers are always different from each other.
I could use gfortran compiler to compile it successfully; however, I found a problem. For instance, when I input 1 and 81 as minimum and maximum values respectively and 0.07 as the percentage, the code always gave me seven different random numbers, which were always smaller than 10, no matter how many times I ran it. What I expect is that the code should give me seven different random numbers which are distributed within 1~81 range, rather than only concentrated within 1~10 range. I do not know why the code gave me the random numbers only concentrating within a certain range. I paste my code below.
Would you anyone give me some suggestions on my problem? Thank you very much in advance.
PROGRAM RANDOM_POSITION
IMPLICIT NONE
REAL percent, val
INTEGER maxi, mini, num, i, l
INTEGER, DIMENSION(1), ALLOCATABLE :: position(:)
PRINT *,'Range for the impurity position(maximum and minimum value):'
PRINT *,'Minimum value:'
READ (UNIT=*, FMT=*) mini
PRINT *,'Maximum value:'
READ (UNIT=*, FMT=*) maxi
PRINT 11,'Percentage of impurity='
11 FORMAT(A23,$)
READ (UNIT=*, FMT=*) percent
num = (maxi-mini) * percent
IF ((maxi-mini) * percent-num .NE. 0.0) THEN
num = num + 1
END IF
PRINT *, num
ALLOCATE (position(num))
CALL RANDOM_SEED()
DO i=1, num ,1
CALL RANDOM_NUMBER(val)
position(i) = NINT(mini + val * num)
CALL JUDGEMENT(position, i, l)
l = 0
DO WHILE (l .EQ. 0)
CALL RANDOM_NUMBER(val)
position(i) = NINT(mini + val * num)
CALL JUDGEMENT(position, i, l)
END DO
PRINT *, position(i)
END DO
DEALLOCATE(position)
STOP
END PROGRAM RANDOM_POSITION
SUBROUTINE JUDGEMENT(arr, j, l)
IMPLICIT NONE
INTEGER j, k, l
INTEGER, DIMENSION(1) :: arr(j)
l = 1
DO k=1, j-1, 1
IF (arr(k) .EQ. arr(j)) THEN
l = 0
EXIT
ELSE
l = 1
END IF
END DO
RETURN
END SUBROUTINE JUDGEMENT

How to check if a real number is a natural number in pascal?

I'm a beginner and I'm trying to write a simple program that will calculate all the dividers of a number. After doing a division I want to write only the dividers that give me a natural number. I can't think of a way to do it.
Loop with dividing the number
For i := 1 to x do
Begin
D := x div i;
WriteLn ('Divider', lp, '. ', x, ' : ', i, ' = ', D);
lp := lp +1;
End;
Here's a hint - rather than checking whether the result of x div i is natural, why not check whether x is divided exactly by i? Meaning that x mod i should be 0.

runtime error in following pascal code

I am trying to factor a given number a, so I have written the following Pascal code:
program prime_factors;
var b:array[1..1000] of integer;
k,i,d,a:integer;
begin
k:=0;
write(' enter number ');
read(a);
while a>1 do
if a mod d =0 then
begin
k:=k+1;
b[k]:=d;
a:=a div d;
end
else
if d=2 then
d:=d+1
else
d:=d+2;
for i:=1 to k do
write(b[i],' ');
readln();
readln();
end.
But when I run it, it gives me error 200 or runtime error, but I can't determine what is problem. I have used k as length of numbers of factors in b array. Should I think what problem is with index k?
you should define D:=2; right after the Begin :D because it's default value is 0.

Resources