Finding prime numbers is giving me errors - c

I wanted to print the divisors of given range of numbers. It works alright. But when I try to modify it to put **** at the end of the prime number's divisors it acts like bizarre.
#include <stdio.h>
int main()
{
int a,start,rounds,b,c,k=0;
printf("Please enter a number to start :");
scanf("%d",&start);
printf("Please enter how many numbers you want to print from that number :");
fflush(stdin);
scanf("%d",&rounds);
for(a=start;a<=start+rounds;a++)
{
printf("\n\nThe divisors of number :%d are \n",a);
for(b=1;b<=a;b++)
{
c=a%b;
if(!c)
{
k++;
printf("%d\n",b);
}
}
//printf("%d",k);
if((k==2)||(k==1))
printf("***\n");
}
getchar();
return 0;
}
PS:- The trick I used to find a prime number is counting how many printf statement has been executed before loop ends. Is there any wrong with it? When I remove // from printf statement it prints like below.
start=========>k
1 =========>1
2 =========>3
3 =========>5
4 =========>8
5 =========>10
Why is that?

if((k==2)&&(k==1))
There is no way in todays computers that k can be 2 and 1 at the same time. Maybe you meant to say if k is 2 OR k is 1 ?

You need to reset k back to 0 in your outer loop
printf("\n\nThe divisors of number :%d are \n",a);
k = 0;
(And, as others have pointed out, you need an || operator rather than && for the final test)

Related

Program in C is showing a wrong result, Odd Number

Enter number of integers to be stored : 5
Enter 5 integers:
1 2 3 4 5
There are 2 even numbers in the set.
There are 3 odd numbers in the set.
Even numbers:
2
4
Odd numbers:
1
3
5
Output:
Sum of Odd Numbers is 51
Sum of Even Numbers is 6
--------------------------------
Process exited after 3.389 seconds with return value 0
Press any key to continue . . .
This is the code:
#include <stdio.h>
int main()
{
int N, n;
printf("Enter number of integers to be stored : ");
scanf("%d", &N);
int count[N];
printf("\nEnter %d integers: \n", N);
for(int n=0;n<N;n++)
{
scanf("%d", &count[n]);
}
//Even and Odd Counter
int even_counter=0, odd_counter=0;
for(n=0;n<N;n++)
{
//even_counter
if(count[n]%2==0)
{
even_counter++;
}
//odd_counter
else
{
odd_counter++;
}
}
printf("\nThere are %d even numbers in the set.", even_counter);
printf("\nThere are %d odd numbers in the set.\n", odd_counter);
//Sorting of Even and Odd
int i=0;
printf("\nEven numbers: \n");
for(n=0;n<N;n++)
{
if(count[n]%2==0)
{
printf("%d\n", count[n]);
}
}
printf("\nOdd numbers: \n");
for(n=0;n<N;n++)
{
if(count[n]%2==1)
{
printf("%d\n", count[n]);
}
}
//Sum of Odd and Even Values
//EvenSummation
int even_lister[i], sumEven, odd_lister[i], sumOdd;
for(n=0;n<N;n++)
{
if(count[n]%2==0)
{
even_lister[i]=count[n];
sumEven+=even_lister[i];
}
else //OddSummation
{
int odd_lister[i], sumOdd, i=0;
odd_lister[i]=count[n];
sumOdd+=odd_lister[i];
}
}
printf("\nSum of Odd Numbers is %d", sumOdd);
printf("\nSum of Even Numbers is %d", sumEven);
}
What's wrong with my program? I've tried everything I knew :(
The odd value is giving strange results.
Here's the part where you calculate the sum of even numbers, which works:
if(count[n]%2==0)
{
even_lister[i]=count[n];
sumEven+=even_lister[i];
}
Now here's the part where you calculate the sum of odd numbers, which doesn't:
else //OddSummation
{
int odd_lister[i], sumOdd, i=0;
odd_lister[i]=count[n];
sumOdd+=odd_lister[i];
}
Do you see the difference? There's an extra line in the second one. In the version that doesn't work, you re-declared some local variables and assigned your values to those local variables. That's why it doesn't work. You didn't do anything with the "original" variables in a higher-up scope that you later print to the screen.
Furthermore, both parts are actually broken because you never initialised either sumEven or sumOdd to 0, so their values are unspecified, and you're adding to unspecified values to create other unspecified values. Whether this bug creates an observable symptom or not is undefined.
Another problem is that you declare your arrays like this:
int even_lister[i];
but i is a variable that you set to 0 and never changed. So those arrays have zero length and every single access to them is illegal. Perhaps you meant to use n instead?
You really need to turn on your compiler warnings and read your code more carefully.

Loop does not run more than once

The output should print the statement "Case #(N): I will become a good boy." a certain number of times depending on user input. It should only print prime numbers of N. This is the latest attempt.
#include<stdio.h>
int main(){
int primeNum;
int primeCount;
int primeCheck;
int caseCount=1;
int caseCheck;
scanf("%d", &caseCheck);//gets number of cases
do {
scanf("%d", &primeNum);
primeCheck = 0;
if (primeNum<=1)
{
caseCount++;
}
for (primeCount=2 ; primeCount<=primeNum/2 ; primeCount++)//checks if number is prime
{
if ((primeNum%primeCount) == 0)//checks if number is not prime
{
primeCheck=1;
}
}
if (primeCheck==0)
printf("Case #%d: I will become a good boy.\n", caseCount);//prints if number is prime
} while (caseCount=caseCheck);//while case counter does not exceed number of cases
return(0);}`
The result of this piece of code when the output is 2 [enter] 4 [enter] 2 is "Case #2: I will become a good boy." Why does it not print more than one time and start from number 2?
Just change while (caseCount=caseCheck); to while (caseCount==caseCheck);
The problem with your code is you're not checking the condition. You're just reassigning a value to a variable.

program that tells if a number is prime

you enter a number and the program will find if the number is prime or not
so when I enter the number 7 for the first time it will show you 'the number is prime'
then I enter 8 and it will show you 'the number is not prime'
after that I re_enter the number 7 and it will show you 'the number is not prime'
I don't know where is the problem
please help me
an example photo from here
and my code is :
#include <stdio.h>
#include <stdlib.h>
int main (void){
int n;
int t;
int isPrime=0;
char var;
while(var!='q'){
printf("q=quit p=prime :");
fflush(stdin);
scanf("%c",&var);
if(var=='p'){
printf("plz put the number value :");
scanf(" %d",&n);
for(t=2;t<=n/2;t++){
if (n%t==0){
isPrime=1;
break;
}
}
if(isPrime==0){
printf("%d is a prime number\n",n);
}
else{
printf("%d is not a prime number\n",n);
}
}
else if(var=='q'){
printf("thank you bye\n");
break;
}
else{
printf("a wrong letter\n");
}
}
return 0;
}
You need to set isPrime to 0 each time the user enters a number. Otherwise, it still holds the value from the previous number.
Move the variable declaration
int isPrime = 0;
inside the while loop.
BTW, isn't that variable name backwards? You set it to 1 (i.e. true) when you discover that there's a number that divides it equally. But that's when the number is not prime.
You forgot to reset isPrime back to zero inside the "while" loop.
By they way, looks like you are doing this as a learning exercise. That's good, there's no better way to learn than to try things out.
Here's a tip in C, any non-zero value is treated as "true", and zero is treated as "false". So instead of this:
if (myFlag==1) { ... do something }
Just write this:
if (myFlag) { ... do something }

C Program to find prime number

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");
}
}

What is wrong with this program to find out the primes between 1-n numbers?

This program is not giving any output for prime numbers.
What is the error in the code ? I have to use while loop only !
There are no compilation errors the program is executing fine but after taking a number as an input this program is not generating the prime numbers.
#include <stdio.h>
int main () {
int num, i=1, j=1, count;
printf ("Enter the no. of terms :\n");
scanf ("%d", &num);
printf ("\nPrime numbers are : \n");
while (i<=num) {
while (j<=i) {
if (i%j==0)
count++;
j++;
}
if (count==2)
printf ("%d\n",i);
i++;
count=0;
}
return 0;
}
What is the error in the code ?
Simple answer
You should be resetting j to 1 after testing each number i for primality.
i++;
count=0;
j = 1;
Longer answer
You can reduce the runtime of this algorithm significantly.
By looping j up to the square root of i, you can make the prime check O(sqrt(i)) instead of O(i).
Since you are searching for prime numbers within a range, you can further speed up the algorithm by using a prime number sieve.

Resources