【问题标题】:How can I write a program to print the prime number from an array which has its index also a prime number如何编写一个程序来打印数组中的素数,该数组的索引也是素数
【发布时间】:2014-11-07 14:11:13
【问题描述】:

我如何即兴发挥下面的代码从索引也是素数的数组中找到素数。 这是我的基本代码:

#include <stdio.h>  
main() {

  int n, i, c = 0;
  printf("Enter any number n:");
  scanf("%d", &n);
  /*logic*/
  for (i = 1; i <= n; i++) {
      if (n % i == 0) {
         c++;
      }
  }
  if (c == 2) {
    printf("n is a Prime number");
  }
  else {
     printf("n is not a Prime number");
  }
  return 0;    
}  

【问题讨论】:

  • 首先不清楚你在问什么。其次,您可以对for 循环进行大量优化:以i = 2 开始,以i&lt;n 结束,如果您的模匹配则它不是质数,否则它是。
  • 我不认为它不清楚。请读两遍
  • 不清楚。您的帖子甚至不包含问题,仅包含标题。您提供的代码不一定与您的问题标题要求的内容有关(除了与质数有关)。你想达到什么目标?
  • IMO:这个问题应该在代码审查中而不是在这里,因为它要求我们审查代码,而不是问我们代码有什么问题它不起作用。
  • 看来问题是:给定a[]ifor (i=2; !IsPrime(a[i]; ) { while (!IsPrime(++i)); } printf("%u", a[i]);,剩下的就是写IsPrime(unsigned x)

标签: c arrays indexing primes


【解决方案1】:

您提供的代码可以像这样优化(但它不适用于 2 和 3)。

bool is_prime( int n )
{

  if ( n % 2 == 0 || n % 3 == 0 ) {
    // If multiple of 2 or 3 it's not a prime
    return false;
  }

  // Search for divisors from 5 to only sqrt(n)
  // Example: 36: (1*36) (2*18) (3*12) (6*6) (12*3) (18*2) (36*1)
  for ( int i = 5; i * i <= n; i += 6 ) {
    // Check only odd numbers
    if ( n % i == 0 || n % ( i + 2 ) == 0 ) {
      // i+4 is not checked cause it's a multiple of 3
      // i is increased by 6 (multiple of 3) and the first i+4 = 9
      return false;
    }
  }

  return true;
}

您使用上述函数查找并存储小于或等于数组素数大小的素数。然后对于每个找到的素数 p,您检查 array[p] 是否是具有相同功能的素数。

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2012-05-13
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多