寻找位于 floor(n^2/2)+1 和 n^2 之间的质数数量

huangapple go评论56阅读模式
英文:

Finding number of primes between floor(n^2/2)+1 and n^2

问题

以下是您的代码的翻译部分:

#include <bits/stdc++.h>
using namespace std;

bool isPrime(int n)
{
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}
int main() {
    int cnt=0;

    for(int i=3;i<=100;i++){
        cnt = 0;
        for(int j=(i^2/2)+1; j<(i^2); j++)
        {
            if(isPrime(j))
            {
                cnt++;
            }
        }
        cout << i << " " << cnt << endl;
    }
}

请注意,您的代码中存在一些错误。特别是在计算平方时,应该使用i * i而不是i^2。修正后的代码可能如下所示:

#include <bits/stdc++.h>
using namespace std;

bool isPrime(int n)
{
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}

int main() {
    int cnt = 0;

    for (int i = 3; i <= 100; i++) {
        cnt = 0;
        for (int j = (i * i / 2) + 1; j < (i * i); j++) {
            if (isPrime(j)) {
                cnt++;
            }
        }
        cout << i << " " << cnt << endl;
    }
}

这应该能够正确计算介于 $floor(n^2/2)+1$ 和 $n^2$ 之间的素数数量。

英文:

I was trying to find a program that returned the number of primes between $floor(n^2/2)+1$ and $n^2$.

#include &lt;bits/stdc++.h&gt;
using namespace std;

bool isPrime(int n)
{
    for (int i = 2; i &lt;= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}
int main() {
	int cnt=0;

	for(int i=3;i&lt;=100;i++){
		cnt = 0;
		for(int j=(i^2/2)+1; j&lt;(i^2); j++)
		{
			if(isPrime(j))
			{
				cnt++;
			}
		}
		cout &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; cnt &lt;&lt; endl;
	}
}

is my code, but I got

3 0
4 0
5 1
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 1
14 0
15 0
16 0
17 1
18 0

... etc, so I don't know what went wrong here.
Thanks for the help in advance!

答案1

得分: 1

在C++中,i^2 进行位异或操作,而不是用于指数,你可以将其替换为 pow(i, 2)i*i

英文:

in C++, i^2 does a bitwise XOR operation, it is not for exponents, you can replace this with pow(i, 2) or i*i

huangapple
  • 本文由 发表于 2023年2月18日 13:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定