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;
FILE *read;
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) ;
fclose(read);
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;
}