给定一个数字n,我们需要找到该数字每个数字的总和,直到该数字成为一个数字为止。如果总和是素数,我们需要打印“是”,如果不是素数,则需要打印“否”。
例子:
Input : 5602
Output: No
Explanation:
Step 1- 5+6+0+2 = 13
Step 2- 1+3 = 4
4 is not prime
Input : 56
Output : Yes
Explanation:
Step 1- 5+6 = 11
Step 2- 1+1 = 2 hence 2 is prime
这个想法很简单,我们可以快速找到数字的递归和。
int recDigSum(int n)
{
if (n == 0)
return 0;
return (n % 9 == 0) ? 9 : (n % 9);
}
一旦计算了递归总和,只需简单地检查它是否为2、3、5或7(这些只是个位数的素数)就可以检查它是否为素数。
C++
// CPP code to check if
// recursive sum of
// digits is prime or not.
#include
using namespace std;
// Function for recursive
// digit sum
int recDigSum(int n)
{
if (n == 0)
return 0;
else
{
if (n % 9 == 0)
return 9;
else
return n % 9;
}
}
// function to check if prime
// or not the single digit
void check(int n)
{
// calls function which
// returns sum till
// single digit
n = recDigSum(n);
// checking prime
if (n == 2 or n == 3 or n == 5 or n == 7)
cout << "Yes";
else
cout << "No";
}
// Driver code
int main()
{
int n = 5602;
check(n);
}
// This code is contributed by Shreyanshi.
Java
// java code to check if
// recursive sum of
// digits is prime or not.
import java.io.*;
class GFG
{
// Function for recursive
// digit sum
static int recDigSum(int n)
{
if (n == 0)
return 0;
else
{
if (n % 9 == 0)
return 9;
else
return n % 9;
}
}
// function to check if prime
// or not the single digit
static void check(int n)
{
// calls function which
// returns sum till
// single digit
n = recDigSum(n);
// checking prime
if (n == 2 || n == 3 || n == 5 || n == 7)
System.out.println ( "Yes");
else
System.out.println("No");
}
// Driver code
public static void main (String[] args)
{
int n = 5602;
check(n);
}
}
// This code is contributed by vt_m
Python
# Python code to check if recursive sum
# of digits is prime or not.
def recDigSum(n):
if n == 0:
return 0
else:
if n % 9 == 0:
return 9
else:
return n % 9
# function to check if prime or not
# the single digit
def check(n):
# calls function which returns sum
# till single digit
n = recDigSum(n)
# checking prime
if n == 2 or n == 3 or n == 5 or n == 7:
print "Yes"
else:
print "No"
# driver code
n = 5602
check(n)
C#
// C# code to check if
// recursive sum of
// digits is prime or not.
using System;
class GFG
{
// Function for recursive
// digit sum
static int recDigSum(int n)
{
if (n == 0)
return 0;
else
{
if (n % 9 == 0)
return 9;
else
return n % 9;
}
}
// function to check if prime
// or not the single digit
static void check(int n)
{
// calls function which
// returns sum till
// single digit
n = recDigSum(n);
// checking prime
if (n == 2 || n == 3
|| n == 5 || n == 7)
Console.WriteLine ( "Yes");
else
Console.WriteLine("No");
}
// Driver code
public static void Main ()
{
int n = 5602;
check(n);
}
}
// This code is contributed by anuj_67.
PHP
输出:
No