集合的前N个元素:编一个程序,按递增次序生成集合M的最小的N个数,M的定义如下:
(1)数1属于M;
(2)如果X属于M,则Y=2x+1和Z=3x+1也属于M;
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10000
int main(){
int n,max,Y[MAXSIZE],Z[MAXSIZE],num[MAXSIZE],i=0,j=0,h,a,term;
scanf("%d",&n);
num[0]=1;
while(i<=n){
Y[i]=2*num[i]+1;
Z[i]=3*num[i]+1;
num[++j]=Y[i];
num[++j]=Z[i];
i++;
}
for(a=0;a<=j;a++){
for(h=a;h<=j;h++){
if(num[a]>num[h]){
term=num[a];
num[a]=num[h];
num[h]=term;
}
}
}
for(h=0;h<=j;h++){
if(num[h]==num[h+1]){
for(a=h+1;a<=j;a++){
num[a]=num[a+1];
}
}
}
for(h=0;h<n;h++){
printf("%d ",num[h]);
}
return 0;
}
不知道哪里出了问题显示错误
#include<cstdio>
using namespace std;
const int N = 20002;
int a[N],b[N];
//a是2x+1,b是3x+1
int n,fa=1,fb=1,ra=0,rb=0,x=1,h=1;
//x为最开始的一个数,h做统计
int main() {
scanf("%d",n);
while(h<=n) {
printf("N=%d",x);
a[++ra]=x*2+1;
b[++rb]=x*3+1;
if(a[fa]<b[fb]) x=a[fa++];
else if(a[fa]>b[fb]) x=b[fb++];
else x=a[fa++],fb++;
h++;
}
return 0;
}