Written by @Tuncay_Pashayev.
In this problem there are two numbers and . We have to find a prime number that it has the biigest sum of digits, between and . If there are multiple prime numbers with same sum, we have to print biggest one. If there is no any prime number between and we have to print .
First we have to check if the number is prime. To do this we are going from 2 to square root of number. If there is no any divisor till there, that means there won't be any divisor bigger than square root and that means our number is prime, otherwise it is not prime. After checking of the number is prime or not, we have to find the number's sum of digits and print the biggest prime number that has it.
int max_prime = -1, max_sum = -1;Giving to max_prime and max_sum, because if there won't be any prime number we have to print .
for (int i = a; i <= b; i++)Checking all the numbers from to .
if (i == 1)
continue;If is equals to we have to pass this, because is not a prime number.
bool is_prime = true;Let's think that our number is prime.
for (int j = 2; j <= sqrt(i); j++)
{
if (i % j == 0)
{
is_prime = false;
break;
}
}Checking if there is a divisor between and square root of . If there is at least one divisor, that means our number is not prime and there is no meaning to continue.
if (is_prime)If our number is prime, we can find it's sum of digits.
int sum = 0, number = i;Set the value of sum to . If we do our operations with , we can lose it's value.
while (number != 0)
{
sum += number % 10;
number /= 10;
}Finding sum of digits of our number.
if (sum >= max_sum)
{
max_sum = sum;
max_prime = i;
}If the sum is bigger than already we have found, we are setting this sum as biggest one and also setting this number as biggest prime number.
cout << max_prime;Printing the biggest prime number.