使用 C++ 查找仅由素数数字(2、3、5 和 7)组成的第 n 个数
在这个问题中,我们给定一个数字 N。我们的任务是查找仅由素数数字(2、3、5 和 7)组成的第 n 个数。
仅由素数数字(2、3、5、7)组成的序列是:2、3、5、7、22、23、25、27、32、33...
让我们举个例子来理解这个问题:
Input: N = 6 Output: 23
解决方案方法
解决该问题的一种简单方法是找到给定索引 i 处的数字,即找到该序列的项,为此,我们将观察该序列。
我们有四个不同的素数,因此生成的序列可以被视为一个四位数字系统。在这个数字系统中,我们有 4x 个长度为 x 的数字。
现在要解决问题,我们有了一个序列,在这个序列中我们将找到构成这些数字的数字的长度。然后我们将计算第 N 个数字并打印所需的数字。
为了使用长度找到第 N 个数字,我们将从长度为 (x-1) 的第一个数字开始计数,然后计算这个 N。
示例
程序说明我们解决方案的工作原理
#include <iostream>
#include <math.h>
using namespace std;
void findNthNumber(int n){
long x = 1;
long lastNum = 0;
while (true) {
long currNum = lastNum + pow(4, x);
if (lastNum < n && currNum >= n)
break;
x++;
lastNum = currNum;
}
for (int i = 1; i <= x; i++) {
for (long j = 1; j <= 4; j++) {
if (lastNum + pow(4, x - i) < n)
lastNum += pow(4, x - i);
else {
if (j == 1)
cout<<"2";
else if (j == 2)
cout<<"3";
else if (j == 3)
cout<<"5";
else if (j == 4)
cout<<"7";
break;
}
}
}
}
int main(){
int N = 32;
cout<<N<<"th number made of prime digits is ";
findNthNumber(N);
return 0;
}输出
32th number made of prime digits is 257
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP