c - Command terminated when inputting large number -
how come message "command terminated" when try input large number (around 10 million)? program displays whether number prime or not.
see code below:
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> int main ( int argc, char *argv[] ) { unsigned long long number; bool prime ( unsigned long long ); printf ("enter positive integer greater 1: "); scanf ("%llu", &number ); prime( number ) ? printf ( "%llu prime.\n", number ): printf ( "%llu not prime.\n", number); return exit_success; } bool prime ( unsigned long long number ) { unsigned long long i, j; bool isprime[number + 1]; ( = 2; <= number; i++ ) isprime[i] = true; ( = 2; <= number - 1; i++ ) ( j = 1; i*j <= number; j++ ) isprime[i*j] = false; return isprime[number]; }
the problem attempt create array isprime
on stack larger available memory. should create on heap instead, using
bool *isprime; isprime = malloc((number + 1) * sizeof *isprime);
do once obviously, not every call function prime
notice if want know if number prime, need search far square root of number factor - , if find factor done. makes size of array have create more manageable - involve changes algorithm.
afterthought have problem in logic determines prime number - inner loop starts j=1
means prime numbers marked non-prime. following "slightly improved" code - although there's more make better:
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <math.h> int main ( int argc, char *argv[] ) { unsigned long long number; bool prime ( unsigned long long ); printf ("enter positive integer greater 1: "); scanf ("%llu", &number ); prime( number ) ? printf ( "%llu prime.\n", number ): printf ( "%llu not prime.\n", number); return exit_success; } bool prime ( unsigned long long number ) { unsigned long long i, j, sq; bool *isprime; sq = ceil(sqrt(number)); isprime = malloc((sq + 1)*sizeof *isprime); // generate primes square root of number ( = 2; <= sq; i++ ) isprime[i] = true; ( = 2; < sq; i++ ) { // need mark multiples if prime: if(isprime[i]) { // start loop @ 2, not 1! ( j = 2; i*j <= sq; j++ ) { isprime[i*j] = false; } } } ( = 1; < sq; i++) { if (isprime[i] && number%i==0) return false; } return true; }
basic testing:
gcc -wall
generates no errors / warnings
104729
prime (it is); code doesn't crash input of 10000001
(not prime).
Comments
Post a Comment