为什么我的程序认为4是素数?

时间:2015-10-05 12:45:46

标签: java algorithm

知道为什么这个方法为'4'返回true?

private boolean isPrime(int num) {
            if (num < 2) {
                return false;
            }
            for (int i = 2; i < num / 2; i++) {
                if (num % i == 0)
                    return false;
            }
            return true;
}

3 个答案:

答案 0 :(得分:4)

它返回true,因为你的循环从2开始,到num / 2 -1结束,num = 4 1for。这意味着你永远不会进入for循环。

您的for (int i = 2; i <= num/2; i++) 循环应为

O(num)

请注意,循环的运行时间为for (int i = 2; i * i <= num; i++) 。为了提高效率,您可能需要考虑循环

O(sqrt(num))

string passPhrase = "Pasword"; // can be any string string saltValue = "sALtValue"; // can be any string string hashAlgorithm = "SHA1"; // can be "MD5" int passwordIterations = 7; // can be any number string initVector = "~1B2c3D4e5F6g7H8"; // must be 16 bytes int keySize = 256; // can be 192 or 128 private string Encrypt(string data) { byte[] bytes = Encoding.ASCII.GetBytes(this.initVector); byte[] rgbSalt = Encoding.ASCII.GetBytes(this.saltValue); byte[] buffer = Encoding.UTF8.GetBytes(data); byte[] rgbKey = new PasswordDeriveBytes(this.passPhrase, rgbSalt, this.hashAlgorithm, this.passwordIterations).GetBytes(this.keySize / 8); RijndaelManaged managed = new RijndaelManaged(); managed.Mode = CipherMode.CBC; ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); byte[] inArray = stream.ToArray(); stream.Close(); stream2.Close(); return Convert.ToBase64String(inArray); } private string Decrypt(string data) { byte[] bytes = Encoding.ASCII.GetBytes(this.initVector); byte[] rgbSalt = Encoding.ASCII.GetBytes(this.saltValue); byte[] buffer = Convert.FromBase64String(data); byte[] rgbKey = new PasswordDeriveBytes(this.passPhrase, rgbSalt, this.hashAlgorithm, this.passwordIterations).GetBytes(this.keySize / 8); RijndaelManaged managed = new RijndaelManaged(); managed.Mode = CipherMode.CBC; ICryptoTransform transform = managed.CreateDecryptor(rgbKey, bytes); MemoryStream stream = new MemoryStream(buffer); CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read); byte[] buffer5 = new byte[buffer.Length]; int count = stream2.Read(buffer5, 0, buffer5.Length); stream.Close(); stream2.Close(); return Encoding.UTF8.GetString(buffer5, 0, count); }

答案 1 :(得分:3)

更有效的解决方案是检查2,然后检查奇数到sqrt(n),因为任何高于此值的数字都必须意味着有一个小于此的因子。

static boolean isPrime(long num) {
    if (num < 2) return false;
    if (num == 2) return true;
    if ((num & 1) == 0) return false; // must be even
    for (int i = 3, max = (int) Math.sqrt(num); i <= max; i += 2)
        if (num % i == 0) 
            return false;
    return true;
}

答案 2 :(得分:1)

它返回true,因为控件永远不会进入for循环。

for(int i = 2; i < num / 2; i++) { ... }

此处num4num / 22

for(int i = 2; i < 2; i++) { ... }

最初我是2,不小于2.所以i < 2会给出错误 所以你的循环永远不会运行和函数将返回true