H數

H數

H數是指:僅包含質因子2,3,5,7的數。 【示例】2,3,4,5,6,7,8,9,10均為H數;但11不是H數,12是H數,13不是H數......

簡介

所謂H數是指該數除1以外,最多只有2,3,5,7四種因子。如630是H數,而22不是。

判斷方法

用FreeBASIC來實現H數的算法

DECLARE FUNCTION HNUM(X AS INTEGER) AS INTEGER

DIM AS INTEGER I,N,J

INPUT N

I=1 'H數

J=0 '第J個H數

DO

I=I+1

IF HNUM(I)=1 THEN J=J+1

LOOP WHILE J<N

PRINT I

SLEEP

END

FUNCTION HNUM(X AS INTEGER) AS INTEGER '判斷X是否為H數,是H數並返回值1

IF X<>1 THEN

WHILE X MOD 2=0

X=X/2

WEND

WHILE X MOD 3=0

X=X/3

WEND

WHILE X MOD 5=0

X=X/5

WEND

WHILE X MOD 7=0

X=X/7

WEND

END IF

IF X=1 THEN HNUM=1

END FUNCTION

用FreePascal來實現H數的算法

var j,i,n:longint;
function sb(l:qword):boolean;
begin
sb:=false;
if l<>1
then
begin
while l mod 2=0 do l:=l div 2;
while l mod 3=0 do l:=l div 3;
while l mod 5=0 do l:=l div 5;
while l mod 7=0 do l:=l div 7;
if l=1 then sb:=true;
end;
end;
begin
read(n);
repeat
inc(i);
if sb(i) then inc(j);
until j=n;
write(i);
end.

計算方法

用FreePascal來實現求第n個H數的算法

const maxn=2147483647;

var

flag:boolean;

n,i,left,right:longint;

x:int64;

a:array[0..10000]of int64;

procedure sort(l,r: longint);

var

i,j,x,y: longint;

begin

i:=l;

j:=r;

x:=a[(l+r) div 2];

repeat

while a[i]<x do

inc(i);

while x<a[j] do

dec(j);

if not(i>j) then

begin

y:=a[i];

a[i]:=a[j];

a[j]:=y;

inc(i);

j:=j-1;

end;

until i>j;

if l<j then

sort(l,j);

if i<r then

sort(i,r);

end;

begin

a[1]:=1;

left:=1;right:=1;

while left<=right do

begin

x:=a[left]*2;

if x<=maxn

then

begin

flag:=true;

for i:=1 to right do

if a[i]=x then begin flag:=false;break;end;

if flag

then

begin

inc(right);

a[right]:=x;

end;

end;

x:=a[left]*3;

if x<=maxn

then

begin

flag:=true;

for i:=1 to right do

if a[i]=x then begin flag:=false;break;end;

if flag

then

begin

inc(right);

a[right]:=x;

end;

end;

x:=a[left]*5;

if x<=maxn

then

begin

flag:=true;

for i:=1 to right do

if a[i]=x then begin flag:=false;break;end;

if flag

then

begin

inc(right);

a[right]:=x;

end;

end;

x:=a[left]*7;

if x<=maxn

then

begin

flag:=true;

for i:=1 to right do

if a[i]=x then begin flag:=false;break;end;

if flag

then

begin

inc(right);

a[right]:=x;

end;

end;

inc(left);

end;

sort(1,right);

readln(n);

writeln(a[n]);

end.

相關詞條

相關搜尋

熱門詞條

聯絡我們