LF Prime numbers

I'm trying to find how many prime numbers there are in a file. But so far something is wrong I believe that something wrong is with my function down below. Gave comments everywhere where I thought you guys might need but if you don't understand something let me know.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
using namespace std;
//
const char duom [] = "duomenys.txt";
const char rez []  = "rezultatai.txt";
//
int Pirm(int a, int skaic);
//
int main () {

int a, n, Pirminis, skaic;

ifstream fd(duom);
ofstream fr(rez);

fd >> n; // Reads how many numbers are there from file which is n = 3
for (int i = 1; i <= n; i++) {
    fd >> a; // Reads all the numbers in the file which is a = 5, 6, 7
    Pirminis = Pirm(a, skaic);
    cout << "Pirminiu skaiciu is duomenu failo yra: " << Pirminis << endl;
}

fd.close();
fr.close();

return 0;
}
int Pirm(int a, int skaic){
int i = 2;
skaic = 0;
while(a % i == 0)
if(a % i == 0) skaic++;
else i++;
return skaic; // Returning how many prime numbers there should be
}
Hello DdavidDLT,

When I started working with the program Ii found that line 20 should read Pirminis += Pirm(a, skaic);.

Then if you use the code:
1
2
while (fd >> a) // Reads all the numbers in the file which is a = 5, 6, 7
	Pirminis += Pirm(a, skaic);

First you will eliminate the need to read the first number into "n" and this will allow you to read any size file, i.e., any amount of numbers with out knowing how many are there to start with.

Line 21 should follow the for loop or while loop because it only needs done once.

Next is the function "Pirm". As written it does not work to determine a prime number. Using the first number "5" "5 % 2" has a remainder of 1 which makes the while condition false and it is never entered. If you do manage to enter the while loop the if condition, if true, would most likely mean that you do not have a prime number, so adding 1 to "skaic" would produce the wrong answer.

Do a search here on "prime numbers" and you will find many posts on the subject. I used tpb's code (msg http://www.cplusplus.com/forum/beginner/238664/#msg1064719) to test the program and it worked well. Read enough and you will find something to help you figure out.

With the changes I made and the function "Pirm" working properly the program will work. Changing the input file and using the while loop allows for working with any amount of numbers. Which makes it easy to add any new numbers to test.

Hope that helps,

Andy
Topic archived. No new replies allowed.