仅使用质数2、3和5生成序列,然后显示第n个项(C ++) [英] Generating a sequence using prime numbers 2, 3, and 5 only, and then displaying an nth term (C++)
问题描述
我正在研究一个问题,该问题要求使用质数2、3和5生成一个序列,然后在序列中显示第n个数字.因此,如果我要求程序显示第1000个数字,则应该显示它.
I'm working on a problem that asks to generate a sequence using prime numbers 2, 3, and 5, and then displaying then nth number in the sequence. So, if I ask the program to display the 1000th number, it should display it.
我不能使用数组或类似的东西,而只能使用基本的决策和循环.
I can't be using arrays or anything like that, just basic decisions and loops.
我开始研究它并撞到墙...这就是我得到的:
I started working on it and hit a wall... here's what I got:
#include <iostream>
using namespace std;
int main() {
unsigned int n=23;
for(int i=2; i<n; i++){
if(i%2==0){
cout<<i<<", ";
}else if(i%3==0){
cout<<i<<", ";
}else if(i%5==0){
cout<<i<<", ";
}
}
return 0;
}
不幸的是,该代码无法满足要求.它显示诸如14之类的数字,其中包括质数7....这些数字只能除以3个指定的质数(2,3,5).
Unfortunately, that code doesn't do what's required. It displays numbers such as 14, which includes a prime number 7.... The numbers can only be divided by the 3 specified primes (2,3,5).
我找到了一些我想理解的信息,但到目前为止还不确定如何实现它……也许使用了许多for()循环?因此,看来我必须使用2 ^ n * 3 ^ m * 5 ^ k的概念,其中n + m + k> 0.
I found some information that I'm trying to understand, and so far not sure how to implement it... maybe using lots of for() loops? So, it appears I have to use the concept of 2^n * 3^m * 5^k where n+m+k>0.
我想我必须通过一个数字来进行测试,首先检查它是否可以被2 ^ 1 * 3 ^ 0 * 5 ^ 0完全整除,然后再进行2 ^ 0 * 3 ^ 1 * 5 ^ 0的整除,然后2 ^ 0 * 3 ^ 0 * 5 ^ 1,依此类推...只是不确定从哪里开始.
I guess I have to run a number through a test where it checks to see first if it's fully divisible by 2^1 * 3^0 * 5^0, then 2^0 * 3^1 * 5^0, then 2^0 * 3^0 * 5^1, and so on... Just not sure where to begin.
推荐答案
选中此项.
#include <iostream>
using namespace std;
int IsPrime(int var);
int CheckifPrimeGreaterThaFive(int Num);
int GetFactors(int Num)
{
int i =0,j=0;
for (i =2,j=0; i <= Num; i++)
{
if (Num%i == 0)
{
if (1 == CheckifPrimeGreaterThaFive(i))
{
return 1;
}
}
}
return 0;
}
int CheckifPrimeGreaterThaFive(int Num)
{
if ((Num != 2 && Num != 3 && Num != 5) && IsPrime(Num))
{
return 1;
}
return 0;
}
int IsPrime(int var)
{
for (int i = 2; i <= var/2; i++)
{
if (var % i == 0)
return 0;
}
return 1;
}
int main() {
int n=98;
int i, FactorsCount=0;
for(i=2; i<n; i++)
{
if (0 == GetFactors(i))
{
cout<<" "<<i;
}
}
return 0;
}
这篇关于仅使用质数2、3和5生成序列,然后显示第n个项(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!