小编Che*_*gos的帖子

不理解代码来测试数字是否为素数

我在网上找到了这个代码.这不是我自己的.这是一个测试给定数字是否为素数的函数.该代码用于确定数字是否为素数.我只是不明白它是如何工作的.

function test_prime(n)  
{  

  if (n===1)  
  {  
    return false;  
  }  
  else if(n === 2)  
  {  
    return true;  
  }else  
  {  
    for(var x = 2; x < n; x++)  
    {  
      if(n % x === 0)  
      {  
        return false;  
      }  
    }  
    return true;    
  }  
}  

alert(test_prime(25)); 
Run Code Online (Sandbox Code Playgroud)

第一个if和else if语句对我有意义.如果n等于1,则返回false,即1不是素数.否则,如果n等于2,则返回true,因为2是素数.

else语句中的所有内容对我来说都没有意义.如果你调用函数测试25,这不是素数,25%x,x = 2,等于1.那么为什么函数会返回false?

我知道有一些关于for循环我不理解.

javascript primes

2
推荐指数
1
解决办法
269
查看次数

程序的时间复杂度确定两个字符串是否是彼此的排列

我编写了一个程序来确定两个字符串是否是彼此的排列.我试图使用哈希表这样做.这是我的代码:

bool permutation(string word1, string word2) {

    unordered_map<char, int> myMap1;
    unordered_map<char, int> myMap2;
    int count1 = 0;
    int count2 = 0;

    if (word1.length() == word2.length()) {
        for (int i = 0; i < word1.length(); i++) {
            count1++;
            count2++;
            for (int j = 0; j < word1.length(); j++) {
                if (word1[i] == word1[j] && myMap1.find(word1[i]) == myMap1.end()) {
                    count1++;
                }
                if (word2[i] == word2[j] && myMap2.find(word1[i]) == myMap2.end()) {
                    count2++;
                }
            }
            myMap1.insert({word1[i], count1});
            myMap2.insert({word2[i], count2});
        }
    }
    else {
        return …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm hashtable permutation time-complexity

1
推荐指数
1
解决办法
131
查看次数