Related
I wrote up a piece of code to find whether a number is prime or not and here it is.
#include <stdio.h>
void main() {
int i, n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 3) {
printf("It is a prime number");
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
printf("It's not prime number \n");
break;
} else {
printf("It is a prime number \n");
break;
}
}
}
However, when my input is 33, instead of the output printing It's not a prime number, since 33 is divisible by 3 and 11, it prints that It is a prime number.
What is the problem with my code here?
In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:
for (i = 2; i <= n / i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.
And add a return statement here, because the program is already over and doesn't need to continue:
if (n <= 1){
printf("It's not a prime number");
return 0;
}
if (n <= 3){
printf("It is a prime number");
return 0;
}
This also screens off 0, 1, and negative integers which are not prime numbers.
You almost got it right: you just have to make sure the program exits after having established whether a number is prime.
Also, you can stop the loop at n/i.
Last, but not least: main should return a int.
#include <stdio.h>
int main(void){
int i,n;
printf("Enter value for n: \n");
scanf("%d", &n);
if (n <= 3){
printf("It is a prime number\n");
return 0;
}
for (i = 2; i < n/i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
return 0;
}
There are multiple problems:
void main() should be int main()
you should check the return value of scanf and reject negative numbers
0 and 1 are not considered prime numbers.
you should end the program if the number matches the first test.
you output the result after a single test: it is correct if the test if (n % i == 0) is true as you have found a divisor, but if you have not, you should iterate, testing all possible divisors up to and including floor(sqrt(n)).
Here is a modified version:
#include <stdio.h>
int main() {
int i, n;
printf("Enter value for n: ");
if (scanf("%d", &n) != 1) {
printf("input error, not a number\n");
return 1;
}
if (n < 0) {
printf("number should be positive: %d\n", n);
return 1;
}
if (n <= 1) {
printf("%d is not a prime number\n", n);
return 0;
}
for (i = 2; i < n / i; i++) {
if (n % i == 0) {
printf("%d not prime number (divisible by %d)\n", n, i);
return 0;
}
}
printf("%d is a prime number\n", n);
return 0;
}
You might want to try this:
#include <bits/stdc++.h>
int main(){
int i,n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 1){
printf("It is a prime number");
}
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("A prime Number");
return 0;
}
This is happening because in your code for i = 3 and n = 33, if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number".
I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}
For my assignment, my program needs to ask the user which of the five functions he wants to execute. The five functions include:
Summation of a number
Factorial of a number
Fibonacci value of the nth term.
gcd of two numbers
a to the power of b.
The user will be prompted repeatedly until he wishes to exit. All my functions work fine. However, i think i messed up on one of the loops because once i enter which function i want to execute and enter a value, it keeps displaying the answer in an infinite loop.
#include <stdio.h>
#include <math.h>
// function to find summation of a number
int summation(int k) {
int i;
for(i = k; i >= 0; i--) {
k = i + (i-1);
}
return k;
}
// function to find the factorail of a number
int factorial(int num) {
int i;
for(i = num - 1; i > 0; i--) {
num = num * i;
}
return num;
}
// dunxtion to find the fibonacci of the nth term
int fibonacci(int n){
int i, t1 = 0, t2 = 1, nextTerm;
for(i = 1; i <= n; i++) {
if(i == 1) {
printf("%d, ", t1);
continue;
}
if(i == 2) {
printf("%d, ", t2);
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
printf("%d, ", nextTerm);
}
return nextTerm;
}
// function to find the gcd of two numbers
int gcd(int n, int m) {
int i, gcd;
for(i=1; i <= n && i <= m; i++) {
// Checks if i is a factor of both integers
if(n % i == 0 && m % i == 0)
gcd = i;
}
return gcd;
}
// function to find value of n to the power of m
int power(int n, int m) {
return pow(n, m);
}
int main(void) {;
int option ,n, m;
//Asks user for what they want to find
printf("If you would like to find the summation of a number, enter 1 \n");
printf("If you would like to find the factorial of a number, enter 2 \n");
printf("If you would like to find the fibonacci sequence of a number, enter 3 \n");
printf("If you would like to find the gcd of two numbers, enter 4 \n");
printf("If you would like to find the power of a number a to b, enter 5 \n");
printf("If you would like to exit, enter 0 \n");
scanf("%d", &option);
// Enables the program to prompt the user until they wish to exit
while(option != 0) {
switch(option) { //If user wishes to find the summation
case 1: if(option == 1) {
printf("Enter a number: ");
scanf("%d", &n);
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
}
case 2: if(option == 2) { //if user wishes to find factorial of a number
printf("Enter a number: ");
scanf("%d", &n);
while(n >= 0) {//message displayed if an invalid value is entered
if(n < 0) {
printf("invalid value");
}
else {
printf("factorial of %d is %d", n, factorial(n));
}
}
}
case 3: if(option == 3) { //if user wishes to find the fibonacci value of the nth term
printf("Enter a number: ");
scanf("%d", &n);
while(n >= 0) {//message displayed if an invalid value is entered
if(n < 0) {
printf("invalid value");
}
else {
printf("fibonacci of %d is %d", n, fibonacci(n));
}
}
}
case 4: if(option == 4) {
printf("Enter a number: ");
scanf("%d %d", &n, &m);
while(n >= 0 && m >= 0) {
if(n < 0 || m < 0) {//message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("GCD of %d and %d is %d", n, m, gcd(n, m));
}
}
}
case 5: if(option == 5) {
printf("Enter a number: ");
scanf("%d %d", &n, &m);
while(n >= 0 && m >= 0) {
if(n <= 0 || m < 0) {
printf("invalid value");
}
else {
printf("%d to the power of %d is %d", n, m, power(n, m));
}
}
}
default: if(option == 0) {
break;
}
}
scanf("%d", &option);
}
}
First of all, C has unstructured switch statement.
You need to add a break; statement after each of your case body to limit the execution for a particular case to the body mentioned under that case.
Otherwise, by default, (with the absence of a break statement) all the case statements works in fall-through manner. You can read more about it here.
That said, regarding the repeated execution of a single function, there's a serious flaw in most (if not all) of the the logic. For example, let's take this
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
here, you're replying on n becoming 0 at some point to break out of the loop, but you did not modify n, at all.
To elaborate, C uses pass-by-value for argument passing, so for the call, summation(n), inside the function, whatever change you make to the parameter receiving the value of n, is not reflected in the caller, and thus, the n in the caller remains unchanged.
You just need a break statement at the end of every case
like:
case 1: if(option == 1) {
printf("Enter a number: ");
scanf("%d", &n);
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
}
break;
As the control will fall down to next case if no break statement is present.
Well I have been assigned to do the prime factorisation for composite numbers, but the problem is I have hard-coded it till prime numbers:2,3,5,7,11,13,19 and I want to make it general.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void prime(int flag,int num);
int main()
{
int num, flag, i, div;
printf("Enter your number: ");
scanf("%d", &num);
flag = 1;
prime(flag, num);
printf("Press any key to exit.");
getchar();
return 0;
}
void prime(int flag, int num)
{
void factor(int num, int i);
int sq, i, square;
sq = abs(sqrt(num));
if (num == 2)
flag = 1;
else
for (i = 2; i <= sq; i++)
{
if (num % i == 0)
{
flag = 0;
break;
}
else
flag = 1;
}
if (flag == 1)
printf("\n%d is a prime number", num);
else
{
printf("\n%d is not a prime number\n", num);
factor(num, i);
}
}
void factor(int num, int i)
{
for (i = 2; i <= num; i++)
{
again:
if(num % i == 0)
{
num = num / i;
printf("%d x", i);
if (num != (2||3||5||7||11||17||19))
goto again;
}
}
printf("1\n\n");
}
P.S.:Try to make it as simpler as possible.
The problem is after dividing it with smallest prime. i.e. 2 the next step should be check the number whether it is a prime or not. If not, then factorise it but I dont know how to do it.
Plz help.
Thx in advance.
#include <stdio.h>
void factor(int num);
int main(void){
int num;
printf("Enter positive number(more than 1): ");
if(1 != scanf("%d", &num) || num < 2){
printf("invalid input!\n");
return -1;
}
scanf("%*[^\n]");scanf("%*c");//clear upto line end
factor(num);
printf("Press any key to exit...");
getchar();
return 0;
}
void factor(int num){
int i, flag = 0;
if(num == 2){
printf("\n%d is a prime number\n", num);
return ;
}
while(!(num & 1)){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("2 x ");
num >>= 1;
}
for (i = 3; i*i <= num; i += 2){
while(num % i == 0){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("%d x ", i);
num /= i;
}
}
if(!flag)
printf("\n%d is a prime number\n", num);
else if(num != 1)
printf("%d x 1\n\n", num);
else
printf("1\n\n");
}
Replace line,
if (num!=2&& num!=3 && num!=5 && num!=7 && num!=11 && num!=17 && num!=19)
instead of,
if (num!=2||3||5||7||11||17||19)
In function factor, first try dividing by 2 repeatedly, then try every odd number while said odd number squared is less or equal to num. This simple method is a bit redundant as you try and divide by composite numbers, but since you will already have removed all smaller prime factors, num will not be divisible by such composite numbers. Iterating while i * i <= num will stop much earlier than with your current i <= num test.
Try and write code to implement the above algorithm and post it as an edit.
I'm working on this program that should output 10 prime numbers. So my problem is that I dont know how to tell the program to stop as soon as 10 prime numbers have been stored in the array. I tried to do sizeof(primes)/siseof(int) == 10 , but its not working.
Help me please. Thanks in advance
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime ,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[i] = ar[i];
if( sizeof(primes) / sizeof(int) == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\narray :\n");
I'm going to pitch something a bit more in line with your stated intention:
#define MAX_PRIMES 10
int main(int argc, char * argv[])
{
int inval;
int primes[MAX_PRIMES];
int count = 0;
printf("Enter a prime number,\n");
while (count < MAX_PRIMES)
{
scanf("%d", &inval);
if (IsPrime(inval))
{
primes[count] = inval;
count++;
}
else
{
printf("%d is not a prime number\n", inval);
}
}
printf("\nThe elements of the array are:\n");
for (int i = 0; i < MAX_PRIMES; i++)
{
printf(" %d", primes[i]);
}
}
int ar[100] was replaced with int inval because there doesn't seem to be any need to store the input values.
for(i=0;i<n;i++) replaced with while (count < MAX_PRIMES) because the previous version would stop at n whether 10 primes had been found or not.
printf(" %d",ar[i]) was replaced with printf(" %d", primes[i]) because the stated desired output is 10 primes, not the input array.
Could be a stupid tyop or two in there because I haven't run it.
Use a counter variable. Use this as the index of the primes array, because otherwise you'll write outside the bounds of the array if the user enters more than 10 numbers to try.
int ar[100],primes[10],j,n,i,var;
int primesFound = 0;
printf("Enter a prime number,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[primesFound] = ar[i];
primesFound++;
if( primesFound == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Just add a counter
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime number,\n");
int counter = 0; // here you declare a counter
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
counter++ // here you increase your counter
primes[i] = ar[i];
if (counter == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Now, why the if( sizeof(primes) / sizeof(int) == 10) break; doesn't work? Because your primes is an array, which is declared statically and so its size is always a constant, which is equal to 10 * sizeof(int).