因此,请帮我: “sốđẹp”(越南语)是一个数字,其数字平方和是素数。
示例:12是一个“sốđẹp”,因为1 ^ 2 + 2 ^ 2是5,这是素数。
因此,给定1 <= N <= 106,找到放置在N处的“sốđẹp”(用户输入为N)
示例:如果键入“ 1”,程序将显示第一个“sốđẹp”,即11。
如果您输入“ 2”,则会弹出12。
Pascal最好,但是C ++很好。
这是我尝试过的(不起作用)(写为Pascal):
program so_dep;
uses crt;
var n,i,c,b:integer;
function sumdigits(a:integer):integer;
var digits,sum:integer;
begin
sum := 0;
while a <> 0 do
begin
digits := a mod 10;
a := a div 10;
sum := sum + a*a;
end;
sumdigits := sum;
end;
function primecheck(a:integer):boolean;
var prime:boolean;
i:integer;
max:real;
begin
if a = 2 then prime:=true
else if (a <=1) or (a mod 2 = 0) then
prime := false
else begin
prime := true; i := 3; max := sqrt(n);
while i <= max do
begin
if n mod i = 0 then begin
prime := false;exit
end;
i := i + 2;
end;
end;
end;
begin
clrscr;
write('Nhap so N: ');readln(n);
for c := 2 to n do
begin
b := 0;
while b < n do
if primecheck(sumdigits(c)) = true then
begin
i := c;
inc(b);
end;
end;
writeln('"So dep" thu ',n,' la ',i);
readln;
end.
它应该可以工作(这就是我的想法),但是没有。
按“ 1”,输出为0(应为11) 按2或以上,则完全不起作用。
答案 0 :(得分:1)
这应该可以解决问题:
#include <iostream>
#include <cmath> // sqrt
using namespace std; // not recommended, but I'm lazy here.
bool checkNumber(int); // checks if number is a thingamabob
bool isPrime(int); // checks if number is a prime
int main()
{
// input your N
int n = 0;
cout << "Show the n-th number: " << flush;
cin >> n;
// check n validity
if (cin.good() && n > 0 && n <= 106) {
int idx = 0; // which thingamabob-number are we at?
int number = 0; // what is the current number?
while (idx < n) { // run until we have arrived at the n-th thingamabob-number
number++; // check each number sequentially
if (checkNumber(number)) {
idx++; // number is a thingamabob, increment
}
}
cout << "N-th number is: " << number << endl; // we have reached the nth thingamabob-number (loop exited), display it.
}
else {
cout << "enter a number 0 < n <= 106" << endl;
}
return 0;
}
bool checkNumber(int number) {
int digit = 0;
int sum = 0;
while (number > 0) {
digit = number % 10;
sum += digit * digit;
number = number / 10;
}
return isPrime(sum);
}
bool isPrime(int number) {
// standard prime check, check modulo for every number up to sqrt number in steps of 2
if (number == 1) { return false; } // 1 not a prime
if (number == 2) { return true; } // 2 is prime
if (number % 2 == 0) { return false; }
for (int i = 3; i <= ceil(sqrt(number)); i += 2) {
if (number % i == 0) { return false; }
}
return true;
}