Einzelnen Beitrag anzeigen

Benutzerbild von Neutral General
Neutral General

Registriert seit: 16. Jan 2004
Ort: Bendorf
5.219 Beiträge
 
Delphi 10.2 Tokyo Professional
 
#7

Re: Prüfen ob Potenz von 2

  Alt 2. Mär 2008, 15:06
Hi,

Zitat:
Den Logaritmus zu berechnen dürfte afaik langsamer sein als ne schleife zu schreiben, die die 1 zählt.
Ok, dann darf mans sich aussuchen

Delphi-Quellcode:
function Is2erPotenz(Zahl: Integer): Boolean;
var s: Single;
begin
  s := ln(Zahl) / ln(2);
  Result := s = Ceil(s);
end;

// Is nicht optimiert aber funktioniert und dürfte wie gesagt schneller sein als das obere.
// Und man muss Math nicht einbinden.
function Is2erPotenz(Zahl: Integer): Boolean;
var i: Integer;
    tmp: Integer;
begin
  tmp := 0;
  for i:= 0 to 31 do
    if (Zahl and (1 shl i)) shr i = 1 then
      inc(tmp);
  Result := tmp = 1;
end;
Michael
"Programmers talk about software development on weekends, vacations, and over meals not because they lack imagination,
but because their imagination reveals worlds that others cannot see."
  Mit Zitat antworten Zitat