Reputation: 413
I've been writting some codes for my practise and now I have a trouble.
I need to find divisors of inputted number and output them in file.
Example:
Input: 30
Output: 1 2 3 5 6 10 15 30
This is working pretty well, but answers are like: 30 15 10 6 5 3 2 1 (from other side, but I need from 1 to ...)
#include <fstream>
using namespace std;
int main()
{
int sk; // number
ifstream fd ("input.txt");
ofstream fr ("output.txt");
fd >> sk;
for (int i = 1; i < sk++; i++){
if (sk % i == 0) fr << sk/i << " ";
}
fd.close ();
fr.close ();
}
I've tryed this, but not working, what's the problem?
#include <fstream>
using namespace std;
int main()
{
int sk; // number
ifstream fd ("input.txt");
ofstream fr ("output.txt");
fd >> sk;
for (int i = sk; i < 0; i--){
if (sk % i == 0) fr << sk/i << " ";
}
fd.close ();
fr.close ();
}
Upvotes: 0
Views: 105
Reputation: 553
If you need the output from 1 to sk, the for loop has to look like here:
#include <fstream>
using namespace std;
int main()
{
int sk; // number
ifstream fd ("input.txt");
ofstream fr ("output.txt");
fd >> sk;
for (int i = 1; i <= sk; i++)
if (sk % i == 0) fr << i << " ";
fd.close ();
fr.close ();
}
This will output 1 2 3 5 6 10 15 30
Upvotes: 0
Reputation: 356
Your loop has the wrong condition:
for (int i = sk; i < 0; i--){
if (sk % i == 0) fr << sk/i << " ";
}
With the condition i<0 it never enters the loop. It should be:
for (int i = sk; i >0 0; i--){
if (sk % i == 0) fr << sk/i << " ";
}
Upvotes: 0
Reputation: 12715
Instead of outputting sk/i
, output just i
.
Your i is increasing in ascending order. But you are outputting its counterpart factor 1st. Hence it is getting outputted in decreasing order.
Also, in your second loop, change your termination condition to i >= 1:
for (int i = sk; i >= 1; i--){
Upvotes: 2