查找以 1 结尾的输入的下一个素数

我试图找到下一个以 1 结尾的素数。这只显示下一个素数。但我想打印下一个以 1 结尾的素数。


int num=103;

for(l=num+1;;l++)

{

   for(k=2;k<l;k++)

   {

     if(l%k==0)

        break;

   }

   if(k==l)

   {

       System.out.println("Next prime no is:"+l);

       break;

   }    }


慕田峪7331174
浏览 105回答 2
2回答

一只萌萌小番薯

我们可以做这样的事情吗?int num=103;for(l=num+1;;l++){&nbsp; &nbsp;if(l%10==1)&nbsp; &nbsp;{&nbsp; &nbsp; for(k=2;k<l;k++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp;if(l%k==0)&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;if(k==l)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Next prime no is:"+l);&nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}}

千巷猫影

我认为你可以做得比@ShashankGupta 建议的“加 1 并测试后面的每个数字是否以 1 结尾并且是质数”更好。一旦我们找到下一个以“1”结尾的数字(使用算术,而不是循环),我们只需要从那时起检查每十分之一的数字:public static int next_one_prime(int number){&nbsp; &nbsp; // next number ending in '1'&nbsp; &nbsp; number += 1 + Math.floorMod(-number % 10, 10);&nbsp;&nbsp; &nbsp; outer: while (true)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int k = 3; k * k <= number; k += 2)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (number % k == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; number += 10;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue outer;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return number; // next prime ending in '1'&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java