.= 'tag.htm'; break; case 'flag': $pre .= $default_pre .= 'flag.htm'; break; case 'my': $pre .= $default_pre .= 'my.htm'; break; case 'my_password': $pre .= $default_pre .= 'my_password.htm'; break; case 'my_bind': $pre .= $default_pre .= 'my_bind.htm'; break; case 'my_avatar': $pre .= $default_pre .= 'my_avatar.htm'; break; case 'home_article': $pre .= $default_pre .= 'home_article.htm'; break; case 'home_comment': $pre .= $default_pre .= 'home_comment.htm'; break; case 'user': $pre .= $default_pre .= 'user.htm'; break; case 'user_login': $pre .= $default_pre .= 'user_login.htm'; break; case 'user_create': $pre .= $default_pre .= 'user_create.htm'; break; case 'user_resetpw': $pre .= $default_pre .= 'user_resetpw.htm'; break; case 'user_resetpw_complete': $pre .= $default_pre .= 'user_resetpw_complete.htm'; break; case 'user_comment': $pre .= $default_pre .= 'user_comment.htm'; break; case 'single_page': $pre .= $default_pre .= 'single_page.htm'; break; case 'search': $pre .= $default_pre .= 'search.htm'; break; case 'operate_sticky': $pre .= $default_pre .= 'operate_sticky.htm'; break; case 'operate_close': $pre .= $default_pre .= 'operate_close.htm'; break; case 'operate_delete': $pre .= $default_pre .= 'operate_delete.htm'; break; case 'operate_move': $pre .= $default_pre .= 'operate_move.htm'; break; case '404': $pre .= $default_pre .= '404.htm'; break; case 'read_404': $pre .= $default_pre .= 'read_404.htm'; break; case 'list_404': $pre .= $default_pre .= 'list_404.htm'; break; default: $pre .= $default_pre .= theme_mode_pre(); break; } if ($config['theme']) { $conffile = APP_PATH . 'view/template/' . $config['theme'] . '/conf.json'; $json = is_file($conffile) ? xn_json_decode(file_get_contents($conffile)) : array(); } !empty($json['installed']) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . ($id ? $id . '_' : '') . $pre; (empty($path_file) || !is_file($path_file)) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . $pre; if (!empty($config['theme_child']) && is_array($config['theme_child'])) { foreach ($config['theme_child'] as $theme) { if (empty($theme) || is_array($theme)) continue; $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . ($id ? $id . '_' : '') . $pre; !is_file($path_file) and $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . $pre; } } !is_file($path_file) and $path_file = APP_PATH . ($dir ? 'plugin/' . $dir . '/view/htm/' : 'view/htm/') . $default_pre; return $path_file; } function theme_mode_pre($type = 0) { global $config; $mode = $config['setting']['website_mode']; $pre = ''; if (1 == $mode) { $pre .= 2 == $type ? 'portal_category.htm' : 'portal.htm'; } elseif (2 == $mode) { $pre .= 2 == $type ? 'flat_category.htm' : 'flat.htm'; } else { $pre .= 2 == $type ? 'index_category.htm' : 'index.htm'; } return $pre; } ?>javascript - Count the prime numbers from 2 to 100 with simpler code than this - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count the prime numbers from 2 to 100 with simpler code than this - Stack Overflow

programmeradmin0浏览0评论

It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble ing up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced.

How could I get the same result with a simpler code than this one:

var primes=4; 
for (var counter = 2; counter <= 100; counter = counter + 1)
{
    var isPrime = 0;
    if(isPrime === 0){ 
        if(counter === 2){console.log(counter);} 
        else if(counter === 3){console.log(counter);} 
        else if(counter === 5){console.log(counter);} 
        else if(counter === 7){console.log(counter);} 
        else if(counter % 2 === 0){isPrime=0;} 
        else if(counter % 3 === 0){isPrime=0;} 
        else if(counter % 5 === 0){isPrime=0;} 
        else if(counter % 7 === 0){isPrime=0;}
        else {
            console.log(counter);
            primes = primes + 1;
        }
    }
}
console.log("Counted: "+primes+" primes");

It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble ing up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced.

How could I get the same result with a simpler code than this one:

var primes=4; 
for (var counter = 2; counter <= 100; counter = counter + 1)
{
    var isPrime = 0;
    if(isPrime === 0){ 
        if(counter === 2){console.log(counter);} 
        else if(counter === 3){console.log(counter);} 
        else if(counter === 5){console.log(counter);} 
        else if(counter === 7){console.log(counter);} 
        else if(counter % 2 === 0){isPrime=0;} 
        else if(counter % 3 === 0){isPrime=0;} 
        else if(counter % 5 === 0){isPrime=0;} 
        else if(counter % 7 === 0){isPrime=0;}
        else {
            console.log(counter);
            primes = primes + 1;
        }
    }
}
console.log("Counted: "+primes+" primes");
Share Improve this question edited Jun 13, 2018 at 19:21 Will Ness 71.1k10 gold badges103 silver badges186 bronze badges asked Oct 12, 2012 at 4:42 RufioLJRufioLJ 4371 gold badge7 silver badges12 bronze badges 9
  • 1 Related: the Sieve of Eratosthenes – icktoofay Commented Oct 12, 2012 at 4:44
  • I'd first start with trying to understand that code. It's pretty simple. You might be confusing simple for shorter. – sachleen Commented Oct 12, 2012 at 4:44
  • 4 i dont know why "if (isPrime==0)" is right after assigning "isPrime=0". that 'if' is useless – jondinham Commented Oct 12, 2012 at 4:46
  • @sachleen yes really sorry I was trying to say shorter.. – RufioLJ Commented Oct 12, 2012 at 4:48
  • 1 @RufioLJ, the code you posted unrolls an inner loop to increase speed. It is a mon tactic to make code perform better. Prime calculators are known to be extremely CPU intensive. The answer you accepted is poorly written and would take an extremely long time to find primes if you fed it a high bound of primes to find such as 1,000,000 (hint: the inner loop would execute 1 trillion times as currently written). I added a ment how he could improve so 1,000,000 primes would take only 1 billion iterations, but that's still a lot. – Ed Bayiates Commented Oct 12, 2012 at 5:16
 |  Show 4 more ments

6 Answers 6

Reset to default 7

I'm feeling naughty today so:

function printPrimesBetweenTwoAndOneHundredSimply(){

   var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],
   i,
   arrayLength = primes.length;

   for(i = 0; i < arrayLength; i++){
     console.log(primes[i]);
   }

   console.log("Counted: " + arrayLength + " primes");
}

First, you really don't need to use === for this. The standard == will suffice. Second, you can make all of those lines that are the same thing, except for a single digit into one line:

var primes=4; 
for (var counter = 2; counter <= 100; counter = counter + 1)
{
    var isPrime = 0;
    if(isPrime == 0){ 
        if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
        else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0; 
        else {
            console.log(counter);
            primes = primes + 1;
        }
    }
}
console.log("Counted: "+primes+" primes");

You'll also notice that the {} was removed on a few lines. This is because a single line of code following an if (among others) is always considered nested.

Next, we can change your primes = primes + 1; to this: primes++; which just tells primes to increment itself by one. The same can be done for your counter. We also know that isPrime equals "0" because you set it to that a second ago, so we no longer need that if statement:

var primes=4; 
for (var counter = 2; counter <= 100; counter++)
{
    var isPrime = 0;
    if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
    else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0; 
    else {
        console.log(counter);
        primes++;
    }
}
console.log("Counted: "+primes+" primes");

Next, we can do a negative check (!= instead of ==) on the values and bine your else if with your else. Since we're doing a negative check (for this case) we have to switch the ORs (||) to ANDs (&&):

var primes=4; 
for (var counter = 2; counter <= 100; counter++)
{
    if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
    else if(counter % 2 != 0 && counter % 3 != 0 && counter % 5 != 0 && counter % 7 != 0) {
        console.log(counter);
        primes++;
    }
}
console.log("Counted: "+primes+" primes");

There are many other ways to write it, but I felt it more beneficial to you to use what you started with and shorten it from there.

This finds all prime numbers between 2 and 100:

var primes=0; 
var isprime = true;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
    // For now, we believe that it is a prime
    isprime = true;
    var limit = Math.round(Math.sqrt(counter)); // See ment from @AresAvatar, below
    // We try to find a number between 2 and limit that gives us a reminder of 0
    for (var mod = 2; mod <= limit; mod++) {
        // If we find one, we know it's not a prime
        if (counter%mod == 0) {
            isprime = false;
            break; // Break out of the inner for loop
        }
    }

    if (isprime) {
        console.log(counter, limit);
        primes = primes + 1;
    }
}
console.log("Counted: "+primes+" primes");

Of course "simpler" is not defined. :-)

The following can be made much shorter, but has a bit of robustness built in.

// Get primes from 0 to n. 
// n must be < 2^53
function primeSieve(n) {

  n = Number(n);
  if (n > Math.pow(2, 53) || isNaN(n) || n < 1) {
    return;
  }

  var primes = [];
  var notPrimes = {};
  var num;

  for (var i=2; i<n; i++) {
    for (var j=2; j<n/2; j++) {
      num = i*j;
      notPrimes[num] = num;
    }
    if (!(i in notPrimes)) {
      primes.push(i);
    }
  }
  return primes
} 

So if you want less code:

// Get primes from 0 to n. 
// n must be < 2^53
function primeSieve2(n) {
  var primes = [], notPrimes = {};
  for (var i=2; i<n; i++) { 
    for (var j=2; j<n/2; j++)
      notPrimes[i*j] = i*j;
    i in notPrimes? 0 : primes.push(i);
  }
  return primes
}

This is pretty simple (I mean, short):

console.log(2); console.log(3);
var m5=25, m7=49, i=5, d=2, c=2;
for( ; i<100; i+=d, d=6-d )
{
    if( i!=m5 && i!=m7) { console.log(i); c+=1; }
    if( m5 <= i ) m5+=10;
    if( m7 <= i ) m7+=14;
}
c

It is an "unrolled" sieve of Eratosthenes with 2-3-wheel factorization.

On the one hand, we enumerate all the numbers below 100 (and bigger than 3) that are coprime with 2 and 3, as partial sums of 5+2+4+2+4+... , so that there are no multiples of 2 and 3 among thus enumerated numbers.

On the other hand, we discard from among them all the multiples of 5 and 7, by enumerating them as partial sums of 25+10+10+10+... and 49+14+14+14+... . Multiples of 2 and 3 are not there in the first place, and the first multiple of 11 that needs to be discarded by the sieve of Eratosthenes is 121.

This will be simpler for your Question....

 for (int i = 2; i < 100; i++) {
int j = 0;
for (j = 2; j < i; j++)
    if ((i % j) == 0)break;
        if (i == j)
        System.out.print("  " + i);}
发布评论

评论列表(0)

  1. 暂无评论