Code for prime numbers, why only with "sqrt()" [duplicate] - c

This question already has answers here:
Why do we check up to the square root of a number to determine if the number is prime?
(13 answers)
Closed last year.
I wrote a program for finding prime numbers, my problem is that the code only will run correctly, only if I take the square root of the tested number (on the marked line).
When I have int i = input the code wont run.
I know that sqrt() is helpful here but i thought it should work without as well.
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
bool primeNumber(int input)
{
for(int i = sqrt(input); i > 1; i--) // <------- sqrt()
{
if(input % i == 0)
{
return false;
}
} return true;
}
int main()
{
int input;
printf("Pls type in a positive number: ");
scanf("%d",&input);
for(int i = input; i > 1; i--)
{
bool prime = primeNumber(i);
if(prime)
{
printf("%d is a prime number\n",i);
}
}
return 0;
}

Every positive integer has itself as a factor. A number is prime if its only factors are itself and one. If you consider a number non-prime because it has itself as a factor, then you will consider no numbers to be prime.

For starters the function is incorrect. It returns true for example for the number equal to 1 though 1 is not a prime number. Also as the function parameter has the signed integer type int then the user can pass to the function a negative number.
Also you should write a more general function that can work with any unsigned integer type.
As for your question
When I have int i = input the code wont run.
then each number is divisible by itself.
The function can be more efficient and written without using the function sqrt. Except the even number 2 all other prime numbers are odd. So there is no sense to check whether an even number except 2 is a prime number.
bool primeNumber( unsigned long long int input )
{
bool prime = number % 2 == 0 ? number == 2 : number != 1;
for ( unsigned long long int i = 3; prime && i <= number / i; i += 2 )
{
prime = number % i != 0;
}
return prime;
}
And in main you should write
unsigned int input;
printf( "Pls type in a non-negative number: ");
scanf("%u",&input);
for( unsigned int i = input; i > 0; i-- )
{
bool prime = primeNumber(i);
if(prime)
{
printf("%u is a prime number\n",i);
}
}

Related

File Redirection Input inC

I'm creating a program that takes numbers from a separate .txt file and turns them into a factorial and then finds the amount of times each prime has occurred in the factorial.
I have been working on this code for the last few days and after many hours i keep getting stuck on the same thing, it will compile with no errors but when I try file redirection to get an input from another file it stops and acts like it is asking for input on an endless loop.
Any help would be much appreciated!
#include <stdio.h>
int Storage_array[5];
int current_prime, next_prime, factorial, prime_count, prime_number, num, factorial_current, factorial_next_num, current_number, total_number; //various variables used in program
int find_prime_count(int factorial, int prime_number); //3 functions declared below main()
int find_next_prime(int factorial, int current_prime);
int is_prime(int num);
int a, b, c; //utility varbles
main()
{
if((a=scanf("%d", &c)) == EOF) //checks to see if file is empty
{
return 0;
}
for(b=0; b<c; b++)
{
if((a=scanf("%d", &c)) == EOF) //checks to see if reached end of the file
{
break;
}
scanf("%d", &Storage_array[b]); //paces values from file into the storage array
printf("%d! = ", Storage_array[b]); //formatting the output
for(c=0;c<5;c++)
{
if(c=0) //creating a base case
{
current_prime = 2;
}
else
{
current_prime = next_prime; //updates the current prime after the base case
next_prime = find_next_prime(Storage_array[b], current_prime); //performes the outside functions that fine the next prime number within the factorial
prime_count = find_prime_count(Storage_array[b], current_prime); //performs outside function that finds the number of the current prime within the factorial
printf("(%d^%d)",current_prime ,next_prime); //prints the results in proper format
}
}
printf("\n"); //spaces between factorial numbers
}
}
int is_prime(int num) //function that determines if the input number is a prime number or not
{
for(a=2; a<num; a++) //base case knowing lowest prime is 2
{
if (num % a == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is prime
}
}
}
int find_prime_count (int factorial, int prime_number)
{
for(a=0;a<factorial;a++)//tests all possible prime numbers under the input factorial
{
if(a=0) //base case for lowest possible prime in factorial
{
factorial_current = 1;
factorial_next_num = 1;
}
else
{
factorial_current = (a*factorial_next_num);
}
if(factorial_current % prime_number == 0) //determines if the prime number fits into current factorial number
{
current_number = (factorial_current/prime_number); //finds number of times prime number fits in
total_number = (total_number + current_number); //adds total amount of times that prime has fit within the factorial
}
}
return total_number;
}
int find_next_prime (int factorial, int current_prime) //function that determines the next prime within the factorial
{
for(a=current_prime;a<factorial;a++) //checks all possible primes within the factorial
{
if (factorial % current_prime == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is next prime
}
}
}
the text file i have has the following content and is called input.txt
7
67
9
43
0

Floating Point Exception with File Redirection in C

I am working on a program that takes a list of numbers from an input file and then takes the factorial of each number and finds the amount of each prime factor within the factorial. for example: if the input file just had one line that had "4" on it the program would take that file (input.txt) and then output the amount that each prime factor occurs which in this case is three 2's and one 3, (4! = 4*3*2*1 = 2*3*2*2 = (2^3)*(3^1) which would output the following:
4! = (2^3)*(3^1)
Every-time I compile the program it works fine but when i go to input the file ( ./a.out < input.txt) it returns "Floating point exception" and I have gone through the code and placed various printf statements to try and find which section of the code this error is occurring but it always returns the same thing and I was wondering if anyone can help me out. The code and input.txt are down below.
#include <stdio.h>
int Storage_array[5]; // array creating to store the values of the input text file (input.txt)
int current_prime, next_prime, prime_count, prime_number; // variables that involve the calculation and count of prime numbers
int factorial, factorial_current, factorial_next_num; //variables that invlove the handling of the input factorials
int num, current_number, total_number; //variables at help test if a number is prime of not
int find_prime_count(int factorial, int prime_number); //3 functions declared below main()
int find_next_prime(int factorial, int current_prime);
int is_prime(int num);
int a, b, c; //utility varbles
main()
{
if((a=scanf("%d", &c)) == EOF) //checks to see if file is empty
{
return 0;
}
for(b=0; b<c; b++)
{
if((a=scanf("%d", &c)) == EOF) //checks to see if reached end of the file
{
break;
}
scanf("%d", &Storage_array[b]); //paces values from file into the storage array
printf("%d! = ", Storage_array[b]); //formatting the output
for(c=0;c<5;c++)
{
if(c=0) //creating a base case
{
current_prime = 2;
}
else
{
current_prime = next_prime; //updates the current prime after the base case
next_prime = find_next_prime(Storage_array[b], current_prime); //performes the outside functions that fine the next prime number within the factorial
prime_count = find_prime_count(Storage_array[b], current_prime); //performs outside function that finds the number of the current prime within the factorial
printf("(%d^%d)",current_prime ,next_prime); //prints the results in proper format
}
}
printf("\n"); //spaces between factorial numbers
}
}
/* This function takes an integer as input and then determines if it is a prime number by finding the remainder when the input number is divided by all numbers leading up to the input number exept the number itself and 1, if it is a prime number it returns the prime number, if not it returns 0 */
int is_prime(int num) //function that determines if the input number is a prime number or not
{
for(a=2; a<num; a++) //base case knowing lowest prime is 2
{
if (num % a == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is prime
}
}
}
/* This function takes 2 integers as input (a factorial number and a prime number) and then counts the amount of times that prime number can fit into the factorial, if it can divide with a 0 remainder it divides the factorial by that amount and then stores the amount of times before going to next number within the factorial, after it has divided the entire factorial it returns the number of times the prime number fit */
int find_prime_count (int factorial, int prime_number)
{
for(a=0;a<factorial;a++)//tests all possible prime numbers under the input factorial
{
if(a=0) //base case for lowest possible prime in factorial
{
factorial_current = 1;
factorial_next_num = 1;
}
else
{
factorial_current = (a*factorial_next_num);
}
if(factorial_current % prime_number == 0) //determines if the prime number fits into current factorial number
{
current_number = (factorial_current/prime_number); //finds number of times prime number fits in
total_number = (total_number + current_number); //adds total amount of times that prime has fit within the factorial
}
}
return total_number;
}
/* This function takes 2 integers as input (a factorial and a prime number) and then determines the next prime number within the limits of the factorial by finding the next prime number and testing it to see if it is a factor of the factorial */
int find_next_prime (int factorial, int current_prime) //function that determines the next prime within the factorial
{
for(a=current_prime;a<factorial;a++) //checks all possible primes within the factorial
{
for(b=0;b<a;b++)
{
if (a % b == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is next prime
}
}
}
}
input.txt is below
5
46
89
36
0

C program to check whether a number is prime or not

I used the following code and it showed numbers like 49 as prime and not composite. I am new to programming so please help me with the correct code.
#include <stdio.h>
int main()
{
int n;
int i;
scanf ("%d", &n);
for (i=2; i<n; i++)
{
if (n%i==0)
{
printf ("number is composite");
}
else
{
i=i+1;
}
}
printf("number is prime");
return 0;
}
You didn't stop the loop when you discovered that the number was composite, so composite numbers get both messages.
When i is not a factor of n you are adding 1 to i but then the for loop adds 1 again. This means that for every number that is not a factor of n you skip a number.
The printf("number is prime"); is not surrounded by any kind of if, so it will always be printed regardless of whether or not the number is actually prime. Unlike humans, computers won't think twice about printing conflicting information because computers are incapable of interpreting the actions we make them do.
You can optimize your code by checking less numbers. Only check up to the square root of the number.
This code is untested but should work. Note that this only eliminates the checking of factors above the square root, but not any multiples of previously checked factors (e.g. written like this, the program will check if the number is divisible by 2 but also by 4, 6, 8, 10, etc).
#include <stdio.h>
#include <math.h>
int main()
{
int n;
int i;
int isComposite = 0;
scanf ("%d", &n);
for (i = 2; i <= (int)sqrt((double)n); i++){
if (n % i == 0){
printf ("number is composite");
isComposite = 1;
break;
}
}
if (!isComposite){
printf("number is prime");
}
return 0;
}
You can modify your loop as follows -
if(n%2==0 && n!=2){ //if 2's multiple is entered no need of loop just check this
printf("number is composite");
return 2; // for sake I just returned 2
}
for (i=3; i<n;i=i+2)
{
if (n%i==0) // if this is true
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
}
In this way you stop loop as if condition is true and its code in its block us executed .
You should remove i=i+1 line, you increment i already in for (i=2; i<n; i++)
After that, you must put your conditions after the loop for prevent print result at every check.
#include <stdio.h>
int main()
{
int n;
int i;
scanf ("%d", &n);
for (i = 2; i<n; ++i)
{
if (n%i==0)
{
printf ("number is composite, divisible by %d\n", i);
break;
}
printf("i=%d\n", i);
}
if (n%i != 0)
printf("number is prime\n");
return 0;
}
Combining all suggestions and comments gives:
int q= (int) sqrt(n);
if (n%2==0)
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
for (i=3; i<=q; i += 2)
{
if (n%i==0) // if this is true
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
}
the reason you are getting 49 a s composite is because of this line:
else
{
i=i+1;
}
this causes you to skip odd numbers in your check, and 49 is 7*7, therefore the ouput yo get is that it is prime.
Another problem you have is that you do not stop the loop when you get a composite number, and at the end of it you will invoke this line of code regardless of what happens in the loop.
printf("number is prime");
here is a better practice:
create a function that will return 1 if it is prime, and 0 if it is not.
if you realize that it is a composite number, you should return immediately. if you get to the end of the loop, it is definatley a prime number.
also, you can run your loop to the square root of n to gain a smaller amount of iterations, and not until n.
good luck
int isPrime(int n)
{
int i;
for (i = 2; i < (int) sqrt(n) ; i++)
{
if (n % i == 0)
{
printf("number is composite");
return 0;
}
}
printf("number is prime");
return 1;
}
Here you are.
#include <stdio.h>
int main( void )
{
while ( 1 )
{
unsigned int n = 0;
_Bool prime;
printf( "\nEnter a non-negative number (0-exit): " );
scanf( "%u", &n );
if ( !n ) break;
prime = n == 2 || ( n % 2 && n != 1 );
for ( unsigned i = 3; prime && i * i <= n; i += 2 )
{
prime = n % i;
}
printf( "Number %u is %s\n", n, prime ? "prime" : "composite" );
}
return 0;
}
If to enter sequentially
1 2 3 4 5 6 7 8 9 0
then the output is
Enter a non-negative number (0-exit): 1
Number 1 is composite
Enter a non-negative number (0-exit): 2
Number 2 is prime
Enter a non-negative number (0-exit): 3
Number 3 is prime
Enter a non-negative number (0-exit): 4
Number 4 is composite
Enter a non-negative number (0-exit): 5
Number 5 is prime
Enter a non-negative number (0-exit): 6
Number 6 is composite
Enter a non-negative number (0-exit): 7
Number 7 is prime
Enter a non-negative number (0-exit): 8
Number 8 is composite
Enter a non-negative number (0-exit): 9
Number 9 is composite
Enter a non-negative number (0-exit): 0
Another approach to find whether a number is prime or not can be :-`
#include<stdio.h>
void main()
{
int no,i;
char x='y';
printf("Enter a number : ");
scanf("%d",&no);
for (i=2;i<=no/i;i++)
{
if(no%i==0)
{
x='n';
break;
}
}
if(x=='y')
printf("The number is a prime number. ");
else
printf("The number is not prime number. ");
}
The logic here is to limit the number of test cases to (the quotient of the number being tested and the value of the loop counter) since a divisor cannot exceed this quotient.

Determining if a user inputted variable is prime in a do-while loop

so my task is as follows: Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.
I have all of the variable add up correctly however cannot seem to get the function to stop on a prime number. To try to correct this I made the variable "primecheck" and set it to 2++ thinking that it would be every integer above 2 (obviously not possible but one could hope). any assistance would be much appreciated!
int main (void)
{
int sum = 0, num = 0, i = 0, primecheck = 0, two = 2;
primecheck = two++;
do
{
printf ("Enter an integer: ");
scanf ("%d", &num);
if (num % primecheck == 0 && primecheck != num)
{
sum += num;
}
} while (num % primecheck == 0 && primecheck != num);
i = sum;
printf("%s%d%s", "Sum = ", i, "\n");
}
One possibility would be to introduce a function which performs the primality check, which could be done by using check divisions by all smaller numbers and terminate the loops as soon as a prime number is found. An implementation can be found following this link; the code can be refactored to the follwing function for primality testing. The function returns 1 if n is prime and 0 otherwise. The implementation uses an explicit while loop as the requirements apparently demands it.
int is_prime(int n)
{
int i=3;
int flag=0;
if (n%2==0)
{
return 0;
}
do
{
if (n%i==0)
{
flag=1;
break;
}
i+=2;
}
while (i*i<=n);
return flag;
}

Cannot calculate prime factors with a number with 12 digits in C

Im trying to learn alot more about C code by trying to do the examples on the Project Eular Page : http://projecteuler.net/problems
At the moment im trying to work out the highest prime factor from the number 600851475143.
Here is my code:
/* The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?*/
#include <stdio.h>
unsigned long long GetPrimeFactor(unsigned long long number)
{
/* printf("The number you typed was %d\n", number);*/
unsigned long long prime = 2;
unsigned long long LargestPrime = 0;
while (prime != 0)
{
if(number%prime == 0)
{
if(number == prime)
{
if(LargestPrime < prime)
LargestPrime = prime;
printf("End of prime factors \nLargest Prime: %d\nEnding Number: %d\n", LargestPrime, number);
break;
}
else if(LargestPrime < prime)
LargestPrime = prime;
//divide number by prime
number = number/prime;
printf("Prime: %d\n", prime);
}
else
{
//get new prime
prime = nextPrimeNumber(prime);
}
}
}
unsigned long long nextPrimeNumber(unsigned long long input)
{
unsigned long long nextPrimeNumber;
while(input !=0)
{
if( input < 0)
{
printf("The number you have entered is negative\n");
}
else if (input > 0)
{
nextPrimeNumber = input + 1;
if(nextPrimeNumber%2 == 0 && nextPrimeNumber != 2)
{
nextPrimeNumber += 1;
}
while(!isPrime(nextPrimeNumber))
{
nextPrimeNumber += 2;
}
return nextPrimeNumber;
}
}
}
int isPrime(int number)
{
int i;
int prime = 1; //true
if(number == 2)
prime = 0; //false
if(number%2 == 0 || number <= 1)
prime = 0;
else
{
for(i=3; i<sqrt(number) && prime == 1; i+=2)
if(number%i == 0)
prime = 0;
}
return prime;
}
int main(void)
{
unsigned long long number;
printf("Enter a Number: \n");
scanf("%d", &number);
GetPrimeFactor(number);
return 0;
}
This code works for the number 13195 which is in the example, but goes bad when i try the larger numbers and im not sure whats wrong.
output with large number 600851475143: prime: 3 prime: 29 prime: 5108231 etc.
this cant be correct because the number cannot be divisible by 3 anyway.
Cant work out whats going wrong so any help would be great
Signed ints go up to 2147483647, unsigned ints go up to 4294967295, you could use unsigned long long which goes up to 18446744073709551615 and if you need something even bigger use an arbitrary-precision/bignum library like GnuMP ( http://gmplib.org/)
Update to your edited question:
The format specifier for scanf you use does not even read the whole unsigned long long, i read somewhere that you have to use %llu, however on my gcc this does not work, i have to use:
printf("Enter a Number: \n");
scanf("%I64d", &number);
printf("%I64d", number); // <- make sure that this prints the number you
// gave it before even calling GetPrimeFactor()
have you changed scanf?
scanf("%L", &number)

Resources