回 帖 发 新 帖 刷新版面

主题:求出100-110所有的素数,错在哪里?

求出100-110所有的素数;调试时报语法出错,代码如下.请问错在哪里?

int n, i
for n=100 to 110
    for i=2 to sqrt(n)
    if Mod(n,i)= 0 then exit
     if i>sqrt(n) then &
mle_1.text=mle_1.text+string(n)+","
next

next

回复列表 (共3个回复)

沙发

素数是指该数只能被 1和他自己整除的数,
所以应把  sqrt(n) 换为 n-1

板凳

int li_i= 100,li_n
string ls_msg = ''
for li_i= 100 to 110
    for li_n = 2 to sqrt(li_i) 
        if mod(li_i,li_n) = 0 then exit
        if li_n >= int(sqrt(li_i)) then ls_msg = ls_msg + string(li_i) + ','
    next
    //messagebox('','')
next
messagebox('',ls_msg)    

不过这个算法,没有验证它的可行性,还是设个标志较好些!!!!    
        

3 楼

应该改为:
int n, i
for n=100 to 200
    for i=2 to integer(sqrt(n))
    if Mod(n,i)= 0 then exit

    next
     if i>=sqrt(n) then sle_1.text=sle_1.text+string(n)+","
next

注意循环的位置!

我来回复

您尚未登录,请登录后再回复。点此登录或注册