This program is supposed to display the prime numbers in the range of 1-3000, but it only displays the prime numbers from 743-3000. How do I get it to print all prime numbers in the range?
Here is the program:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
main()
{
unsigned long long num, divisible_num;
printf("The prime numbers in the range of 1 - 3000 are: \n");
for(num=1;num<=3000;num++)
{
for(divisible_num=2;divisible_num<=sqrt(num);divisible_num++)
{
if(num%divisible_num==0)
break;
}
if(num%divisible_num!=0)
{
printf("%lu\n", num);
}
}
getchar();
}
The foremost thing to do is to get the sqrt call out of that for loop. You may compute it once. Better still, remove it all together with
for(divisible_num=2;divisible_num * divisible_num<=num;divisible_num++)
A number is prime if it is not divisible by any of the prime numbers less than or equal to the sqrt(num).
int prime = 1;
for(divisible_num=2;divisible_num * divisible_num<=num;divisible_num++) {
if (num % divisible_num == 0) {
prime = 0;
break;
}
}
if (prime) {
//print the num
}
Your outer loop must also start from 2.
When I ran your code it ranged from 1-3000.
I'm not sure what your problem is.
The get char() seems a little out of place.
Also once checking two, you don't have to divide by any more even numbers.
This code works from 3 - 3000
for(num=3;num<=3000;num++)
{
int prime = (num%2 != 0);
long root = sqrt(num);
for(divisible_num=3;prime && divisible_num <= root;divisible_num+=2)
{
if(num%divisible_num==0){
prime = 0;
}
}
if(prime)
{
printf("%lu\n", num);
}
}
Related
im not getting an output for this program, please help
THE QUESTION:
Twin primes are consecutive odd numbers both of which are prime numbers. Write a program which inputs two positive integers A and B and outputs all twin primes in range A to B.
The code is:
#include <stdio.h>
int main(){
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if(num1>num2){
temp=num1;
for(i=num2;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j!=0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k!=0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num2){
printf("\n%d and %d",i,i+2);
}
}
}
else{
temp=num2;
for(i=num1;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j==0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k==0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num1){
printf("\n%d and %d",i,i+2);
}
}
}
return 0;
}
OUTPUT:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\shaun\OneDrive\Desktop> cd "c:\Users\shaun\OneDrive\Desktop\c programming\programs\" ; if ($?) { gcc twin_primes.c -o twin_primes } ; if ($?) { .\twin_primes }
Enter 2 numbers: 8 19
Twin prime numbers are:
PS C:\Users\shaun\OneDrive\Desktop\c programming\programs>
if(p1==1 && p2==1 && (i+2)<=num2)
if(p1==1 && p2==1 && (i+2)<=num1)
You've mixed up with num2 & num1 in above 2 conditions.
If you use num1 instead of num2 and num2 instead of num1, you'll get the output.
Apart from this, there're several logical errors in code.
Logic to find prime number
Initializing variable p1 and p2 in proper place
To solve above 2 problems, I would recommend to learn more about finding prime numbers. I'll add some resources at below, please check those.
Another thing, you're basically writing same code twice. You could make it more simple by just swapping 2 given values when first one is larger than the second one.
Lastly, I'm giving a sample code here. It's one of the way you could follow to write simple but easily understandable solution for your problem.
Sample code:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num)
{
for(int i = 2; i * i <= num; i++)
{
if (num % i == 0) return false;
}
return true;
}
int main()
{
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if (num1 > num2)
{
// swap the numbers. always keeping the first as the smaller one
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 == 1) num1++; // ignoring 1
for(int i = num1; i <= num2 - 2; i++) // running the loop till num2 - 2, so we won't have to check whether i + 2 <= num2
{
if (isPrime(i) && isPrime(i+2))
{
printf("\n%d and %d",i,i+2);
}
}
return 0;
}
Please check below URLs to learn more about prime number and swapping values
C Program to Swap Two Numbers
C Program to Swap two Numbers GFG
Prime Numbers GFG
C Program to Check Whether a Number is Prime or Not
Which is the most efficient way to calculate prime numbers in C?
Quora
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
printf("FAILURE!");
return 0;
}
The point of the task is to make a program for a user to type and try to guess a numper from 1–300 with 8 attempts. If you find the number it shows RIGHT! and if not it guides you by telling that the number is biger/smaller. If you fail in your 8 atemts then it shows failure. The problem is that it shows failure when you fail to guess in your 8 atempts but when you find the number it prints both RIGHT & FAILURE. What should i correct for the program to print failure only when you cant’t find the number within your 8 tries?
My 2 cents, path of least resistance is to simply return rather than break when the user guesses correctly:
if (num == rnum)
{
printf("RIGHT!");
return 0; // program exits here, no FAILURE print
}
You should also seed the rand function with a changing number, like time. With a constant, you'll find your number to guess is the same every time.
srand(time(NULL)); // randomize seed
You should check if they exceeding the 8 try limit before executing the print statement:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
if (times > 8)
{
printf("FAILURE!");
}
return 0;
}
I think you should write return 0; instead of break; after printing RIGHT. because if you guess the rnum it will print RIGHT and breaks out and after that it will print FAILURE too but if you write return 0; it will end the program.
When you break; out after having printed RIGHT! you end up where you print FAILURE! so you need to check this somehow.
Here's my take on it:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num = 0, rnum;
// This game will get boring with a static seed.
// I'm assuming you use this seed for testing only.
srand(4383);
rnum = rand() % 300 + 1;
for(int times = 0; times < 8; ++times) { // simpler loop
printf("Guess the random number between 1-300: ");
// if the user fails to enter a number - make it print FAILURE
if(scanf("%d", &num) != 1) break;
if(num < rnum)
puts("The random number is bigger");
else if(num > rnum) // added "else"
puts("The magic number is smaller");
else
break; // neither less nor greater than rnum so it must be correct
}
if(num == rnum) // added check
printf("RIGHT!\n");
else
printf("FAILURE!\n");
}
Writing a program in C that uses recursion to determine if a number is prime or not. It works until you try it with a prime number above 9431. Anything higher than that gets a stack overflow error. I was wondering if there was some way to fix this.
I haven't really tried anything other than see at which number it fails at, which varies each time.
//Remove scanf error
#define _CRT_SECURE_NO_WARNINGS
//Preprocessor directives
#include<stdio.h>
#include<stdlib.h>
//Recursion function
int PrimeCheck(int choice, int i)
{
//Check if integer i is reduced to 1
if (i == 1)
{
return 0;
}
else
{
//Check to see if number choice is divisible by value i
if (choice % i == 0)
{
return 1;
}
//Call the function again but reduce the second variable by 1
else
{
return PrimeCheck(choice, i - 1);
}
}
}//End PrimeCheck function
//Main function
main()
{
//Assign needed variables
int choice, num;
//ask for user input
printf("Please enter a number between 2 and %i:", INT_MAX);
scanf("%i", &choice);
//Check for numbers outside the range
if (choice < 2 || choice > INT_MAX)
{
printf("Please try again and enter a valid number.\n");
system("pause");
return 0;
}
//Call the PrimeCheck "looping" function
num = PrimeCheck(choice, choice / 2);
//Display result for the user
if (num == 0)
{
printf("%i is a prime number.\n", choice);
}
else
{
printf("%i is NOT a prime number.\n", choice);
}
system("pause");
}//End main
The output should be "____ is a prime number" or "____ is NOT a prime number"
The actual output above 9431 is a stack overflow error.
One help, reduce tests.
PrimeCheck(choice, choice / 2); iterates about choice/2 times when only sqrt(choice) times needed.
Instead of starting at choice/2
PrimeCheck(choice, sqrt(choice));
Better code would avoid small rounding error and integer truncation with
PrimeCheck(choice, lround(sqrt(choice)));
or if you have access to an integer square root function:
PrimeCheck(choice, isqrt(choice));
For 9431, this will reduce stack depth by about a factor of 50 - and speeds the program.
Speed performance tip. Rather than iterate from choice / 2 or sqrt(choice) down to 1. Go up from 2 to sqrt(choice). Non-primes will be detected much faster.
Sample
#include <stdbool.h>
#include <stdio.h>
bool isprimeR_helper(unsigned test, unsigned x) {
// test values too large, we are done
if (test > x/test ) {
return true;
}
if (x%test == 0) {
return false; // composite
}
return isprimeR_helper(test + 2, x);
}
bool isprimeR(unsigned x) {
// Handle small values
if (x <= 3) {
return x >= 2;
}
// Handle other even values
if (x %2 == 0) {
return false;
}
return isprimeR_helper(3, x);
}
int main(void) {
for (unsigned i = 0; i < 50000; i++) {
if (isprimeR(i)) {
printf(" %u", i);
}
}
printf("\n");
}
Output
2 3 5 7 11 13 17 19 ... 49991 49993 49999
Implementations notes
Do not use if (test*test > x). Use test > x/test
test*test may overflow. x/test will not.
Good compilers will see nearby x/test and x%test and compute both effectively as one operation. So if code has x%test, the cost of x/test if often negligible.
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
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}