c++ - “并非所有控制路径都返回值”是什么意思以及如何排除故障。(C++)
问题描述
我正在尝试为分配创建一个函数,该函数找到两个素数加起来为给定的总和。指令要求
“编写一个 C++ 程序,通过列出从 4 到 100,000 的所有偶数以及添加到相同数字的两个素数来研究猜想。请确保您编写了一个无法表示为的偶数的情况两个素数之和(尽管这不应该发生!)。要显示的适当消息是“猜想失败!” 您可以通过查看 4 到 100,000 之间的所有整数是否都可以表示为两个素数之和来测试此代码。应该有很多失败。
在修改它以将其集成到主程序之前,我已经创建并测试了“showPrimePair”功能,但现在我遇到了这个特定的错误
“C4715 'showPrimePair':并非所有控制路径都返回值”
我已经进行了研究以尝试修复该错误,但它仍然存在。
#include <iostream>
#include <stdio.h>
//#include <string> // new
//#include <vector> //new
//#include <algorithm>
using namespace std;
bool isPrime(int n);
//bool showPrimePair(int x);
//vector <int> primes; //new
const int MAX = 100000;
//// Sieve Sundaram function // new
//
//void sieveSundaram()
//{
// bool marked[MAX / 2 + 100] = { 0 };
// for (int i = 1; i <= (sqrt(MAX) - 1) / 2; i++)
// for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1)
// marked[j] = true;
//
// primes.push_back(2);
// for (int i = 1; i <= MAX / 2; i++)
// if (marked[i] == false)
// primes.push_back(2 * i + 1);
//}
// Function checks if number is prime //links to showPrimePair
bool isPrime(int n) {
bool prime = true;
for (int i = 2; i <= n / 2; i++)
{
if (n % i == 0) // condition for nonprime number
{
prime = false;
break;
}
}
return prime;
}
// Function for showing prime pairs ( in progress) Integer as a Sum of Two Prime Numbers
bool showPrimePair(int n) {
bool foundPair = true;
for (int i = 2; i <= n / 2; ++i)
// condition for i to be a prime number
{
if (isPrime(i) == 1)
{
// condition for n-i to be a prime number
if (isPrime(n - i) == 1)
{
// n = primeNumber1 + primeNumber2
printf("%d = %d + %d\n", n, i, n - i);
foundPair = true;
break;
}
}
}
if (foundPair == false) {
cout << " Conjecture fails!" << endl;
return 0;
}
}
// Main program in listing conjectures for all even numbers from 4-100,000 along q/ 2 primes that add up to same number.
int main()
{
//sieveSundaram();
cout << "Goldbach's Conjecture by Tony Pham " << endl;
for (int x = 2; x <= MAX; x++) {
/*if (isPrime(x) == true) { //works
cout << x << " is a prime number " << endl;
}
else {
cout << x << " is not a prime number " << endl;
}*/
showPrimePair(x);
}
cout << "Enter any character to quit: ";
cin.get();
}
解决方案
首先,您可以使用埃拉托色尼筛算法找到所需范围内的所有素数。接下来,您可以将所有找到的素数插入哈希集中。最后,对于范围内的每个数字n
,您可以尝试所有p
不超过的素数n/2
,并探测 是否n-p
也是素数(只要您有哈希集,此操作就非常快)。
推荐阅读
- javascript - 如何修复“错误类型错误:data.slice 不是函数”?
- python - 在python中导入网格
- apache-spark - Spark 自定义日志记录
- python-3.x - 为什么我的仪表板应用程序无法正确更新?
- java - 如何使用 Spring-Boot 在 Java 项目中使用 Clojure 库?
- git - 仅显示作为我的提交之一的祖先的提交?
- angular5 - 当 TAB 超出 ag-grid 的最后一个单元格时需要添加新行
- java - 区分“无法为对象分配空间”异常
- python-3.x - 我在 Google 应用引擎上使用 Cloud SQL。在控制台中添加新用户并重新部署我的应用程序后,新用户似乎无法登录?
- ios - iOS PWA 特殊 mailto 链接在 pwa 浏览器中打开选项卡。并停留在空白标签