I'm new to the world of programming. Until now, the exercises were very easy for me, until I came up to this one. The goal is:
"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.
The program is working, (I've edited the code) but now I think a lot of values are missing (for example, the value 12 which was given as an example don't appear)
it would be really appreciated if someone could show me where are the errors :)
Thanks in advance!
I've just verified and I can't really initialize them because they are replaced by other values later ( numberis replaced by sum, numerator is replaced by number and denominator is replaced by j. But thanks anyway!
You need to be dividing your number as you go, or else you get stuck in an infinite loop. Make a placeholder variable to store the original number so you can print it later. Also, for your isPrime function, the for loop should be starting at j=2 (or you end up trying to divide by 0, starting at j=1 would mean everything will appear as not prime)
#include <iostream>
usingnamespace std;
bool isPrime (int number);
bool isDivisable (int numerator, int denominator);
int main()
{
// I used j rather than i as I initially thought that would mean less changes
for(int j=1; j<1000; j++) // i used 100 when testing as I could easily check the early numbers
{
int i=j; // this is so you have an original copy of the number
int sum=0;
for(int dividor=2;dividor<j;)
{
if (i%dividor==0)
{
i/=dividor; // this divides i by the divisor
sum=sum+dividor;
}
else
{
dividor++;
}
}
if (isPrime(sum))
{
cout<<j<< "\n";
}
}
// you can ignore this really, it just means it doesn't autoclose once the program ends
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
bool isPrime (int number)
{
for(int j=2;j<number;j++) // note the j=2
{
if (isDivisable(number, j))
{
returnfalse;
}
else
{
returntrue;
}
}
}
bool isDivisable (int numerator, int denominator)
{
return numerator%denominator==0;
}
For those who are working on this problem if future: this code prints both prime numbers and numbers with prime factor sum of a prime. If you want to exclude the primes, in line 25 add && sum!=0 to the condition. This will eliminate all primes from the list leaving you with the numbers that can actually be broken down.