所以我想我已经解决了这个问题,但过了一段时间,我意识到我的代码所做的就是确保所有的输入都是质数,并且前3个输入小于第4个。或者反之亦然,如果它是一个从大到小的素数序列,那么我如何正确地确保我的所有4个素数都是连续的?质数越高,每个质数之间的差距就越大。所以我被难住了。此外,flag++还检查是否所有4个输入都是质数。如果4个函数都是质数,那么我的函数返回TRUE。
if(input2 > input1) //This is to know if the sequence is going up or going down, in this case, it's up
while (x <= input4) { //Creates all prime numbers while X is lesser than or equal to input4
while (isprime(x) == 0)
x++;
if (isprime(x)) { //If x is a prime number, we check if it's one of the inputs, if all 4 inputs are consecutive prime integers, then flag will be 4 after the loop, and we'll know that it's a prime sequence
if (x == input1)
flag++;
if (x == input2)
flag++;
if (x == input3)
flag++;
if (x == input4)
flag++;
}
x++;
}发布于 2016-03-21 00:17:09
我打算让函数从input1开始,如果下一个质数不是input 2,我会让它立即返回0,如果下一个质数是input 2,则重复这个过程,直到input4。感谢你对Erastothenes Sieve的反馈,然而,我不允许使用数组来做这件事,Eratothenes的Sieve需要它。所以我将实现我想要的东西。对于那些因为他们有同样的问题而在谷歌上搜索的人,你可以这么做。
y = 0, x = input1; //This
if(input2 > input1) //This is to know if the sequence is going up or going down, in this case, it's up
while (x <= input4) { //Creates all prime numbers while X is lesser than or equal to input4
while (isprime(x) == 0)
x++;
if (isprime(x))
y++;
if (isprime(x)) { //If x is a prime number, we check if it's one of the inputs, if all 4 inputs are consecutive prime integers, then flag will be 4 after the loop, and we'll know that it's a prime sequence
//If y is equal to 1, that means that the prime number found is the next input
if (x == input1 && y == 1) {
flag++;
y = 0;
}
if (x == input2 && y == 1) {
flag++;
y = 0;
}
if (x == input3 && y == 1) {
flag++;
y = 0;
}
if (x == input4 && y == 1) {
flag++;
y = 0;
}
}
x++;
}发布于 2016-03-21 00:48:20
您可能会对Wilson's theorem感兴趣,它指出
对于候选素数n,n是素数当且仅当((n- 1)!+1)
n=0
虽然我知道您要求用C语言提供一个解决方案,但这样的解决方案并不容易提供,因为有各种各样的“大数字”包,等等,可能会选择这些包。但是,为了证明这个定理的实现是可能的(如果有足够的语言支持,这并不困难),我将指出,在Clojure ( Java VM的Lisp变体)中,这可以实现为
(defn is-prime [n]
(= (mod (+' (apply *' (range 2 n)) 1) n) 0))这里不需要数组,因为任何数字的“质数”都可以直接确定,而不需要知道任何其他质数的值。它确实需要计算潜在大数字的阶乘,因此“大数字”数学软件包可能非常有用,但它确实允许直接确定任何给定的数字是否为质数,因此通过迭代从最低值输入到最高值输入的所有数字,它将允许您确定是否存在任何中间质数。
祝你好运。
发布于 2016-03-21 07:30:14
你怎么吃大象的?One bite at a time。我们需要将这个问题分解成一系列的小步骤。从那里开始,一切都很简单。
我不是向你展示任何代码,而是想为你展示算法的要点。一些评论建议,最好的方法是使用数组来创建筛子。
我认为应该使用数组,但不一定是用来创建筛子的。而是处理用户输入的值。然而,根据你老师荒谬的要求,我们不允许数组。这很好--这意味着我们的算法可以处理任何数量的输入。这是相当短视的,但哦,好吧。
以下是步骤(听起来其中一些步骤已经解决了)。
我希望在这个程序中看到一些函数:
bool isPrime(int value);
int nextPrime(int startingPrime);因此,在按顺序对值进行排序后,您将看到类似以下内容:
isPrime(value1) && value2 == nextPrime(value1) && value3 == nextPrime(value2) && value4 == nextPrime(value3)https://stackoverflow.com/questions/36115940
复制相似问题