Hi, I have written a program, that would find the prime factors of all numbers upto 1000. there should be 999 outputs. but the outs arent really the sum, what should i do? my code is.
#include <iostream>
usingnamespace std;
int main()
{
int i=2;
int y=0;
for (int k=2;k<1000; k++)
{
int i=2;
int y=0;
int x=k;
while(i<x)
{
if (x%i==0)
{
x=x/i;
y=y+i;
}
else
{i++;}
}
int z;
z=x+y;
cout<<z<<endl;
}
}
#include <iostream>
int main()
{
int i=2;
int y=0;
for (int k=2; k<1000; k++)
{
int x=k;
while(i<x)
{
if (x%i == 0)
{
x = x/i;
y = y+i;
}
else
{i++;}
}
int z;
z = x+y;
std::cout << z << std::endl;
}
}
there are no 999 outputs, since your for loop runs from 2 to 999 --> 998outputs
line 16, you are dividing integers, no idea if you know what that means.
for example 10/3 = 3 and not 3.33333...
Do you mean list the prime factors of each number like this:
2: 2
3: 3
4: 2
5: 5
6: 2 3
if so, then the easiest thing to do would be to calculate all primes <1000 and the loop through all integers between 2 and 1000, and check to see if divisible by all of the primes under 1000.
Shouldn't i be set to 2 and y to 0 before the while loop?
Offtopic: Your code is non intuitive. What is the purpose of i, y, x, k and z? Use suggestive names to make it easier to understand how you're going at the problem.
I have found the problem. Its not in the sourcecode. Its actually in the display window of the program.when upto k<298 the program works fine. but when k=299 it omits the first result 2. when 300 than it omits 2 and 3, and go on!! Is there any way so that I can expand the display window of the command. I am using windows 7 and codeblocks....
I have found the problem. Its not in the sourcecode. Its actually in the display window of the program.when upto k<298 the program works fine. but when k=299 it omits the first result 2. when 300 than it omits 2 and 3, and go on!! Is there any way so that I can expand the display window of the command. I am using windows 7 and codeblocks....
Output to a file.
LowestOne wrote:
You do have a code error though, "i" needs to be reset to 2 for every factor that it finds.
Either use ofstream or redirect from cmd (Windows)/terminal (Unix).
For cmd:
prog > file.txt
For terminal:
./prog > file.txt
Assuming prog is your executable name, all output using cout will be printed in file.txt instead of the screen.
Obviously you will need to navigate to the directory where your executable is (using cd and dir (Windows)/ls (Unix)).
For Windows type cd /? to see what it does. man ls for Unix.