这是我目前的代码,但它使用了分区(我不允许这项任务)。如何在不使用/
或%
运算符的情况下重写此代码?
public class PrimeNumber {
public static void main(String[] args) {
int num = 31;
int c = 0;
for (int i = 2; i < num; i++) {
if ((num - (num / i) * i) == 0)
c++;
}
if (c == 0)
System.out.println("prime");
else
System.out.println("not prime");
}
}
答案 0 :(得分:2)
这是嵌套循环(半伪代码)的一种方式:
int x ;
//check if x is a multiple of any two factors < x
for (int i1 = 2 ; i1 < x ; i1++) {
for (int i2 = i1 ; i2 < x ; i2++) {
prod = i1 * i2 ;
if (prod > x) break ;
if (prod == x) return "x is not prime" ;
}
}
return "x is prime" ;
这应该是相当有效的,但对于大数字你想要改进它。您可以执行一项检查:if (i1 == i2 && prod > x) return "x is prime"
这将消除大量迭代。
答案 1 :(得分:1)
从2开始循环,因为那是第一个素数:
for (int i=2; i <=100; i++) {
BigInteger bi = new BigInteger(""+i);
if (bi.isProbablePrime(9999)) {
System.out.println("Prime: " + i);
}
}
答案 2 :(得分:0)
这是我刚刚为c#找到的代码,我认为它应该可行:
using System;
class Program
{
static void Main()
{
//
// Write prime numbers between 0 and 100.
//
Console.WriteLine("--- Primes between 0 and 100 ---");
for (int i = 0; i < 100; i++)
{
bool prime = PrimeTool.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}
//
// Write prime numbers between 10000 and 10100
//
Console.WriteLine("--- Primes between 10000 and 10100 ---");
for (int i = 10000; i < 10100; i++)
{
if (PrimeTool.IsPrime(i))
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}
}
}