Welcome to collectivesolver - Programming & Software Q&A with Examples. A website you can trust. All programs tested and work.

Contact: aviboots(AT)netvision.net.il


Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Survey Junkie is the #1 place online for your audience to earn rewards for their opinion.

100%
Managed VPS Hosting
Affordable. Secure. Your Own Virtual Private Hosting. Faster than AWS and Rackspace

Bonsai Boy of New York Bonsai Trees and Accessories
Liquid Web - Highest Level of Performance and Security with Managed Dedicated Servers

Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

21,340 questions

28,140 answers

573 users

How to check whether a number can be expressed as sum of two prime numbers in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>

int isPrime(int n) {
    if (n < 2 || (n % 2 == 0 && n != 2)) {
        return 0;
    }

    int count = floor(sqrt(n));
    for (int i = 3; i <= count; i += 2) {
        if (n % i == 0) {
            return 0;
        }
    }
    return 1;
}

int main(void) {
    int n = 38;
    bool has_primes = false;

    for (int i = 2; i <= n / 2; i++) {
        if (isPrime(i)) {
            if (isPrime(n - i)) {
                std::cout << n << " = " << i << " + " << n - i << "\n";
                has_primes = true;
            }
        }
    }

    if (!has_primes)
        std::cout << n << " cannot be expressed as a sum of two prime numbers";

    return 0;
}




/*
run:

38 = 7 + 31
38 = 19 + 19

*/

 




answered Jan 12 by avibootz
...