Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

#include <iostream> #include <cmath> using namespace std; bool isprime(int n) { if (n <…

  1. User

    #include #include using namespace std;

    bool is_prime(int n) { if (n < 2) return false; for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true; }

    int digit_sum(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; }

    int main() { int a, b; cin >> a >> b; int max_digit_sum = -1; int max_prime = -1; for (int i = a; i <= b; i++) { if (is_prime(i) && digit_sum(i) > max_digit_sum) { max_digit_sum = digit_sum(i); max_prime = i; } } cout << max_prime; if (max_prime == -1) cout << -1; return 0; }

  2. Assistant

    The program takes two integer inputs, a and b, and finds the largest prime number between a and b whose digit sum is also the largest.

    First, it defines a function is_prime that checks if a number is prime. It returns false if the number is less than 2 or if it is divisible by any number from 2 to the square root of the number.

    Next, it defines a function digit_sum that calculates the sum of the digits in a number. It initializes the sum to 0 and uses a while loop to add each digit to the sum and then remove it from the number until the number becomes 0.

    In the main function, it reads in the values of a and b. It initializes two variables max_digit_sum and max_prime to -1. It then iterates over each integer between a and b. If the integer is prime and its digit sum is greater than the current max digit sum, it updates the max digit sum and the max prime.

    Finally, it outputs the max prime. If there are no prime numbers in the range [a, b], it outputs -1.