# Alex's exercise Chapter 6 Ex3

• 01-25-2013
Valentas
Alex's exercise Chapter 6 Ex3
Code:

```/*Design a program that finds all numbers from 1 to 1000 whose prime factors, when added together, sum up to a prime number (for example, 12 has prime factors of 2, 2, and 3, which sum to 7, which is prime). Implement the code for that algorithm.*/ #include <iostream> using namespace std; int primes(int n); bool isPrime(int divisor); bool check(int result); int main() {     // Check numbers from 1 to 1000     for (int i = 2; i <= 1000; ++i)     {         int result = primes(i);         if (check(result))         {             cout << i << endl;         }     } } bool isPrime(int divisor) {     for (int j = 2; j <= divisor/2; j++)     {         if (divisor % j == 0)             return false;     }     return true; } int primes(int i) {     int p = i;     int divisor = 2;     int sum = 0;     while (p != 1)     {         cout << "p: " << p << endl;         cout << "le divisor: " << divisor << endl;         if (isPrime(divisor))         {             if (p % divisor == 0)             {                 p = p / divisor;                 sum += divisor;             }             else             {                 divisor += 1;             }         }     }     return sum; } bool check(int result) {     for (int i = 2; i <= result / 2; i++)     {         if (result % i == 0)             return false;     }     return true; }```
My code does not do what is asked.

Could anyone check it up?
• 01-25-2013
Shakti
Define "does not do"
• 01-25-2013
Valentas
Quote:

Originally Posted by Shakti
Define "does not do"

The program should print numbers whose factors sum up to prime numbers. However, there is something wrong with int primes(n) function.

I get into infinite loop and print statements show that p : 5 and divisor : 4 and it stays like that in that loop. I cannot find a flaw in my logic.
• 01-25-2013
King Mir
Quote:

Originally Posted by Valentas
The program should print numbers whose factors sum up to prime numbers. However, there is something wrong with int primes(n) function.

I get into infinite loop and print statements show that p : 5 and divisor : 4 and it stays like that in that loop. I cannot find a flaw in my logic.

Use a debugger like gdb or what's built in to you IDE to step through loop, and verify what each variable each iteration. If you have a logic error, this will find it.