C Program to find prime number - c

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

Related

To find if entered no. is prime or not. The output i am getting is quite weird

Following is the code i have written to find if the entered no. is prime or not. please tell what to correct as the output is coming quite weird.
` #include<stdio.h>
main()
{
int n,i;
printf("enter a no.");
scanf("%d", &n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
printf("its prime");
else{
printf("not prime");
}
}
}
The output is shown in the picture below:
I believe you don't understand how modulo works. According to Wikipedia, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).
When you ask if(n%i==0) you're asking if n when divided by i gives a remainder 0 or not. Take n=6 and i=3. Then n%i==0 evaluates to "TRUE", because 6 is divisible by 3. Your algorithm tries to print the number is prime when it's quite the opposite. The following code should work:
#include<stdio.h>
main()
{
int n,i;
printf("enter a no.");
scanf("%d", &n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
printf("not prime");
return 0; //Since you've already proved it's composite, there's no need to waste time.
}
}
printf("Number is prime."); //If your number is not prime, this line won't execute as your program will exit with that return statement.
}
If you are concerned about the answer getting printed multiple times, then you should not print the answer statement inside the for loop. Alternatively, make the use of the 'break' statement.
Also, make your prime-checking conditions correct.
#include<stdio.h>
main() {
int n, x;
printf("Enter a number");
scanf("%d", &n);
for (x = 2; x <= n / 2; x++) {
if (n % x == 0) {
printf("Not prime");
break;
}
else {
printf("Prime");
break;
}
}
}

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 }

Write a program that multiplies user entered number till product of these numbers reach 1000

I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}

Receive two inputs in C language

I want a program that can get two integers from user and put the sum of those inputs in a variable, after that checks that is sum more than 5 or not ? (I know I can do it with if , ... but I want to do it with while). I myself did it but it has some problems, would you mind saying what is the problem and how can I debug it ? Here is my code :
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
}
return 0;
}
This line is only scanning for 1 integer (%i with a 2 format, indicating only take 2 digits.):
scanf("%2i", &ui1, &ui2);
But it seems you expected to receive two integers.
This will leave the second argument, ui2, uninitialized.
(It should fill ui1 successfully, at least)
Try instead:
scanf("%i %i", &ui1, &ui2);
Try including the scanf statement into the loop, it will no longer be an infinite loop... (also need to dereference the integers, see EDIT)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:\n");
//scanf("%2i", &ui1, &ui2);
int sum = 10;//(so that it will enter the loop at least once)
//sum = ui1+ui2;
while(sum > 4)
{
printf("enter number 1:\n");
scanf("%i", &ui1); //EDIT &
printf("enter number 2:\n");
scanf("%i", &ui2); //EDIT &
sum = ui1+ui2;
}
printf("result is: %d\n", sum);
getchar();//so you can see the result;
getchar();
return 0;
}
Actually while is a loop stmt not a conditional checker
if you want conditional checker use if...else series , switch etc
Note: in your code loop starts if (sum > 5) and never ends (infinate "Whats up !")
sum = ui1+ui2;
while(sum > 5) ///loop starts if (sum > 5) and never ends (infinate "Whats up !")
{
printf("Whats up !"); // (infinate "Whats up !")
}
if(sum > 5)
{
//greater stuff
}
else
{
//lower stuff
}
See Tutorial Here conditionals Stmts
You need to reset the "sum", because otherwise the while loop will be true FOREVER.
Second the input scanf is simply wrong.
Here the correct code
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%d %d", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 4) { printf("Whats up !");
sum=0;}
return 0;
}
I'm not sure that i got what you want to do... but if you simply want to check the sum of the two integers using the while statement, you can put a break inside the while loop and everything will work :)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
break;
}
return 0;
}
As others told you, using a if is the best solution

Problem determining if a number is an Armstrong Number

I'm trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can't figure it out.
Any help is appreciated.
Code attached below.
#include<stdio.h>
int fun(int);
int main()
{
int x,a,b,y=0;
printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
scanf("%d",&a);
for(int i=1 ; i<=3 ; i++)
{
b = a % 10;
x = fun(b);
y = x+y;
a = a/10;
}
if(y==a)
printf("\narmstrong number");
else
printf("\nnot an armstrong number");
return 0;
}
int fun(int x)
{
int a;
a=x*x*x;
return (a);
}
The primary problem is that you don't keep a record of the number you start out with. You divide a by 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.
Your other problem is that you can't look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function fun() would be better named cube(); in my code below, it is renamed power() because it is generalized to handle N-digit numbers.
I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for power() - one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn't measure it in this context. If compiled with -DDEBUG, it includes diagnostic printing - which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I've wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I've added checks to the scanf() to head off problems, another important basic programming technique.
I've checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.
#include <stdio.h>
#include <stdbool.h>
#ifndef DEBUG
#define DEBUG 0
#endif
static int power(int x, int n)
{
int r = 1;
int c = n;
while (c-- > 0)
r *= x;
if (DEBUG) printf(" %d**%d = %d\n", x, n, r);
return r;
}
static bool isArmstrongNumber(int n)
{
int y = 0;
int a = n;
int p;
for (p = 0; a != 0; a /= 10, p++)
;
if (DEBUG) printf(" n = %d, p = %d\n", n, p);
a = n;
for (int i = 0; i < p; i++)
{
y += power(a % 10, p);
a /= 10;
}
return(y == n);
}
int main(void)
{
while (1)
{
int a;
printf("Enter the number you want to identify as an Armstrong number or not: ");
if (scanf("%d", &a) != 1 || a <= 0)
break;
else if (isArmstrongNumber(a))
printf("%d is an Armstrong number\n", a);
else
printf("%d is not an Armstrong number\n", a);
}
return 0;
}
One problem might be that you're changing a (so it will no longer have the original value). Also it would only match 1, 153, 370, 371, 407. That's a hint to replace the for and test until a is zero and to change the function to raise to the number of digits.
#include<stdio.h>
#include <math.h>
int power(int, int);
int numberofdigits(int);
//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is.
int main()
{
int input;
int digit;
int sumofdigits = 0;
printf("enter the number you want to identify as an Armstrong or not:");
scanf("%d",&input);
int candidate = input;
int digitcount = numberofdigits(input);
for(int i=1 ; i <= digitcount ; i++)
{
digit = candidate % 10;
sumofdigits = sumofdigits + power(digit, digitcount);
candidate = candidate / 10;
}
if(sumofdigits == input)
printf("\n %d is an Armstrong number", input);
else
printf("\n %d is NOT an Armstrong number", input);
return 0;
}
int numberofdigits(int n);
{
return log10(n) + 1;
}
int power(int n, int pow)
{
int result = n;
int i=1;
while (i < pow)
{
result = result * n;
i++;
}
}
What was wrong with the code:
No use of meaningful variable names, making the meaning of the code hard to understand; remember code is written for humans, not compilers.
Don't use confusing code this code: int x,a,b,y=0; is confusing, do all vars get set to 0 or just y. Always put vars that get initialized on a separate line. It makes reading easier. Go the extra mile to be unambiguous, it will pay off big time in the long run.
Use comments: If you don't know what an armstrong number is, than it will be very hard to tell from your code. Put a few meaningful comments in so people know what your code it supposed to do. This will make it easier for you and others because they know what you meant to do and can see what you actually did and solve the difference if need be.
use meaningful routine names WTF does fun(x) do?. Never name anything fun() it's like fact free science, what's the point?
Don't hardcode things, your routine only accepted armstrong3 numbers, but if you can hardcode then why not do return (input == 153) || (input == 370) || ....
Okay so, the thing is that there are also Armstrong numbers that are not just 3 digits for example 1634, 8208 are 4 digit Armstrong numbers, 54748, 92727, 93084 are 5 digit Armstrong numbers and so on. so to check the number is Armstrong or not, here's what I did.
#include <stdio.h>
int main()
{
int a,b,c,i=0,sum=0;
printf("Enter the number to check is an Armstrong number or not :");
scanf("%d",&a);
//checking the digits of the number.
b=a;
while(b!=0)
{
b=b/10;
i++;
}
// i indicates the digits
b=a;
while(a!=0)
{
int pwr = 1;
c= a%10;
//taking mod to get unit place and getting its nth power of their digits
for(int j=0; j<i; j++)
{
pwr = pwr*c;
}
//Adding the nth power of the unit place
sum += pwr;
a = a/10;
//Dividing the number to give the end condition
}
if(sum==b)
{
printf("The number %d is an Armstrong number",b);
}
else
{
printf("The number %d is not an Armstrong number",b);
}
}
/*
Name: Rakesh Kusuma
Email Id: rockykusuma#gmail.com
Title: Program to Display List of Armstrong Numbers in 'C' Language
*/
#include<stdio.h>
#include<math.h>
int main()
{
int temp,rem, val,max,temp1,count;
int num;
val=0;
num=1;
printf("What is the maximum limit of Armstrong Number Required: ");
scanf("%d",&max);
printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);
while(num <=max)
{
count = 0;
temp1 = num;
while(temp1!=0)
{
temp1=temp1/10;
count++;
}
if(count<3)
count = 3;
temp = num;
val = 0;
while(temp>0)
{
rem = temp%10;
val = val+pow(rem,count);
temp = temp/10;
}
if(val==num)
{
printf("\n%d", num);
}
num++;
}
return 0;
}
Check No. is Armstrong or Not using C Language
#include<stdio.h>
#include<conio.h>
void main()
{
A:
int n,n1,rem,ans;
clrscr();
printf("\nEnter No. :: ");
scanf("%d",&n);
n1=n;
ans=0;
while(n>0)
{
rem=n%10;
ans=ans+(rem*rem*rem);
n=n/10;
}
if(n1==ans)
{
printf("\n Your Entered No. is Armstrong...");
}
else
{
printf("\n Your Entered No. is not Armstrong...");
}
printf("\n\nPress 0 to Continue...");
if(getch()=='0')
{
goto A;
}
printf("\n\n\tThank You...");
getch();
}
If you are trying to find a armstrong number the solution you posted is missing a case where your digits are great than 3 ...armstrong numbers can be greater than 3 digits (for example 9474). Here is the code in Python, the logic is simple and it can be converted to any other language.
def check_armstrong(number):
num = str(number)
total=0
for n in range(len(num)):
total+=sum(int(num[n]),len(num))
if (number == total):
print("we have armstrong #",total)
def sum(input,power):
input = input**power
return input
check_armstrong(9474)
Here's a way to check whether a number is armstrong or not
t=int(input("nos of test cases"))
while t>0:
num=int(input("enter any number = "))
n=num
sum=0
while n>0:
digit=n%10
sum += digit ** 3
n=n//10
if num==sum:
print("armstronng num")
else:
print("not armstrong")
t-=1
This is the most simplest code i have made and seen ever for Armstrong number detection:
def is_Armstrong(y):
if y == 0:
print('this is 0')
else:
x = str(y)
i = 0
num = 0
while i<len(x):
num += int(x[i])**(len(x))
i += 1
if num == y:
print('{} is an Armstrong number.'.format(num))
break
else:
print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)

Resources