# Thread: How To Fix This Issue In A Program For Finding Prime Numbers

1. ## How To Fix This Issue In A Program For Finding Prime Numbers

This is a program testing for prime numbers in a specific range,using an .in file and writing to an .out one.
My question is why after a certain range of number e.g.when i set 234 to 234353 it outputs giberish?Also any ideas to NOT have a space character after the last number would be apreciated because my method obviously is wrong for some reason..
Code:
```#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;

bool ISPRIME(int K)
{

if (K == 2)
return false;
if (K % 2 == 0)
return false;
if (K%3==0&&K!=3)
return false;
if (K%5==0&&K!=5)
return false;
if (K%7==0&&K!=7)
return false;

for (int d = 11; d <= (int)sqrt((double)K); d=d+2)

if (K % d == 0)

return false;

return true;

}
int main(){
int N;
int M;

read = fopen ( "function.in" , "r" ) ;

fscanf ( read , "%d" , &N ) ;

fscanf ( read , "%d" , &M ) ;
int K = ( N < M ) ? (N+1) : (M+1) ;

int d = ( N < M ) ? (M-1) : (N-1) ;

FILE *write;
write=fopen("function.out","w");
while (K<=d)
{

if (ISPRIME(K)==true&&K==d)
fprintf(write,"%d",K);

else if(ISPRIME(K))
{fprintf(write,"%d",K);
fprintf(write," ");}

K++;

}

fclose(write);
return 0;
}``` 2. Your compiler probably supports 16-bit integers. The maximum value of a signed 16-bit integer is about 32767. If you attempt to work with larger values than an int can hold, the result is undefined behaviour.

I'll leave the exercise of avoiding a space after the last number as an exercise. You will learn more by puzzling out a solution yourself, than you would by being given a solution.

Unrelated to your questions: 2 is prime, but your function does not detect that. There are better ways of computing the square root of an integer than sqrt(). If you do a search for similar topics, you will find better approaches. 3. Unrelated to your problem, but important. Your indentation is horrible. You need to fix that. Also don't use fopen, fscanf, fclose, fgets, etc in C++. Use streams (see tutorial on site if you aren't familiar with them). 4. Once I solve it like this:

Code:
```#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
for(int i = 2; i <= 100 ; i++)
{
int b = 1;
for(int j = 2;j<=i;j++)
{

if(i==j)
continue;
else if(i % j == 0)
b =0;
}
if(b)
cout<< i << " ";
}
cout << endl;
system("PAUSE");
return 0;
}```
So why not only this:

Code:
` for(int i = 253; i <= 234353 ; i++)` Popular pages Recent additions cpp, file access, prime number 