Reputation: 59
I want to make an algorithm which return whether is ginen number odd or even without using built-in functions like mod, div, odd(). Only solution that I made up is following, but it isn't much robust and only for numbers higher then 0
Var
n: integer;
begin
ReadLn(n);
While (n not in [1, 0]) do
n:=n-2;
if n = 1 then
WriteLn('odd')
else
WriteLn('even');
end.
Thank you for your help.
Upvotes: 2
Views: 7912
Reputation: 37
You can use the number truncation:
var
n: integer;
begin
readln(n);
if(n-(n/2)*2 = 1) then
writeln('odd')
else
writeln('even');
end.
Upvotes: 0
Reputation: 26356
I never really used J&W Pascal but I know many bit manipulation operators are missing.
However I did use Pascal's successor Modula2, and in M2 one cast an integer to a set the same size. If that also works for classic Pascal then you could do
Type
TIntBitset = [0..31]; // or whatever your word size is.
if 0 in TIntBitSet(i) then
begin
(* odd! *)
end;
Upvotes: 1
Reputation: 72312
Can you use cos
? If so, try
abs(cos(n*1.570796326794896619231321691639751442)) > 0.9
It should really be = 1
but we cannot use a perfect value of π/2 and there'll be a small error in cos...
Upvotes: 0
Reputation: 5858
well, to make it work with negative numbers you can just check if the number is negative and if it is, multiply with -1
(or just use abs
).
The only issue with your algorithm is efficiency; runs in o(n). Some other ideas:
Check if the last digit is 0,2,4,6,8 (really good if the number is given as a string/array) In each step of your algorithm increase the subtracted number till you hit negative then reverse the process. For example, let's say we want to check 64:
So 10 steps instead of 63.
Note that after the first reverse, we decrease the subtracted number on each step because we know that it's less than 2x the number we subtract. Of course, you can create a ton of variations, some of them which are probably more efficient.
Upvotes: 2
Reputation: 12562
If a number is odd, its last bit is 1, and 0 otherwise. You could use a bitwise operator to test against integer(1), which is represented as 0..00001.
My Pascal skills are a little rusty, but it should be something similar:
var
n: integer;
begin
readln(n);
if(n&1 = 1) then
writeln('odd')
else
writeln('even');
end.
Upvotes: 0