#include <stdio.h>
#include <stdlib.h>
//this function checks if the given number prime or not
int prime_check(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
//the problem is that when i entered the integer 2 i got that "the number is not prime" output
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}
If the selected number is 2, the for loop is never entered because i < number is initially false. The function then reaches the end without returning a value.
If a function is declared to return a value but does not, and the calling function attempts to use the return value, this triggers undefined behavior in your program, which basically means that no particular result is guaranteed.
Related to this, you have a logic error. The body of the for loop has a return statement in every path so no more that one iteration of the loop will occur. This causes all odd numbers to be reported as prime.
You only need to perform the % check inside of the loop. If that condition is not met, then continue on with the loop. If the loop exits, then you know you have a prime number and can return 0.
int prime_check(int number)
{
for (int i = 2;i<number;i++){
if (number % i == 0){
return 1;
}
}
return 0;
}
Also, you can reduce the number of loop iterations by changing the condition to i<=number/i (which is mathematically the same as i*i<=number but avoids overflow), since you don't need to check values greater than the square root of the number in question.
You can't enter to for loop only if the condition i < number is TRUE
SO you should check if number = 2 and number < 2 before your for loop
The new version of your code:
#include <stdio.h>
#include <stdlib.h>
int prime_check(int number) {
if (number == 2) {
return 0;
} else if (number < 2) {
return 1;
} else {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
}
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}
Related
I want my code to print "YES" if there is digit 7 in the entered number, and otherwise print "NO".
When I use while(T != 0) for test cases, my code prints "YES" for all the numbers - even for number 45. Without while(T != 0) my code runs perfectly.
Where is my mistake?
#include <stdio.h>
int main() {
int T;
scanf("%d", &T);
while (T != 0) {
int X;
scanf("%d", &X);
int flag, result;
while (X != 0) {
result = X % 10;
if (result == 7) {
flag = 1;
}
X = X / 10;
}
if (flag == 1) {
puts("YES");
} else {
puts("NO");
}
T--;
}
return 0;
}
After trying out your code, the main issue was not with the "while" test. Rather, in the code your test flag was not being reset so once the a value was found to have the digit "7" in it, all subsequent tests were noted as being "YES". With that, following is a refactored version of your code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int T;
printf("How many numbers to test: "); /* Clarifies what the user is being asked for */
scanf("%d", &T);
while (T != 0)
{
int X;
printf("Enter a number to be tested: "); /* Again, lets the user know what to enter */
scanf("%d", &X);
int flag = 0, result;
while (X != 0)
{
result = X % 10;
if (result == 7)
{
flag = 1;
}
X = X / 10;
}
if (flag == 1)
{
puts("YES");
}
else
{
puts("NO");
}
flag = 0; /* Needs to be reset after being set and before next check */
T--;
}
return 0;
}
Some things to note.
Although not really needed, verbiage was added as prompts to clarify to the user what needed to be entered for values.
Most importantly, the flag variable gets initialized to zero and then subsequently gets reset to zero after each test has been completed.
With those bits addressed, following is some sample terminal output.
#Vera:~/C_Programs/Console/Seven/bin/Release$ ./Seven
How many numbers to test: 4
Enter a number to be tested: 3987
YES
Enter a number to be tested: 893445
NO
Enter a number to be tested: 8445
NO
Enter a number to be tested: 58047
YES
Give that a try and see if it meets the spirit of your project.
I recently wrote a program in C for a calculator. To produce a function that checks if the user input is a prime number or not (amongst other functions).
I essentially used this code (excluding all other functions):
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^
This code above produces the errors
I am not sure why the code produces an error for the value 9 (I fixed that above by adding the condition: if (operand1 == 9), but I don't understand why 9 is seemingly the only value that results in an incorrect solution (It would say 9 was prime, but not any other number give an incorrect result).
One other bug that I remidied with an extra condition statement was the value of 2.
Before adding the extra conditional statement in the main function: if (ioperand1 == 2), the value 2 would always come up as a non prime number.
I originally found this solution to check for prime numbers online, and I still don't understand why the for loop starts from 2.
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0 || ioperand1 == 2)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1 || operand1 == 9)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^This code above fixed the problem, though I don't undesttand why the problem existed in the first place.
TL;DR:
I don't know why this code doesn't work without the extra conditional statements:
if (operand1 == 9) in function definition,
and
if (ioperand1 == 2) in main function.
If anyone could help clear this up, I'd appreciate it.
It is because your prime checking loop does not iterate. It always returns on the first iteration. It must run to completion, and then the number will be prime. So
int testForPrime(int operand1) {
if(operand1 < 2) {
return 0;
}
int sr = (int)round(sqrt(operand1));
for(int i = 2; i <= sr; i++) {
if (operand1 % i == 0) {
return 0;
}
}
return 1;
}
This is my code. I failed to use the break keyword after the printf function in order to break out of the loop. When I enter a negative number or zero, it doesn't prompt me again to re-enter.
#include <stdio.h>
#include <cs50.h>
int get_positive_int(void);
int main (void)
{
get_positive_int();
}
int get_positive_int(void)
{
int i;
i = get_int("Integer: ");
while (true)
{
if (i<1)
{
return i;
}
else
{
printf("%i", i);
}
}
}
The algorithm in the function get_positive_int() is wrong:
You need to place i = get_int("Integer: "); inside of the while loop.
Your if condition:
if (i < 1)
is wrong as that would return i if i is a negative integer or 0. If you want to return i when i is a positive integer or 0 you should use if(i >= 0).
Note that you can also place:
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
after the call to maintain the occurrence of a read error. But if you want to only return INT_MAX then, you do not need to do so and can omit it since this would fit to the conditional statement ``if(i >= 0)` and its body.
The code is then:
int get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
else if (i >= 0)
{
return i;
}
printf("%i", i);
}
}
Side note: If you don´t want to count 0 as positive integer, you need to have i >= 1 as the condition of the if statement.
As you said in the comments you only want to continue if i is a positive integer and exit if i is a negative characters or 0:
void get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i < 1)
{
return;
}
printf("%i\n", i);
}
}
Note that in this case, the return type of get_positive_int shall be void instead of int and it should omit to return i as it is not necessary to return any value from the function.
The question is that show the digits which were repeated in C.
So I wrote this:
#include<stdio.h>
#include<stdbool.h>
int main(void){
bool number[10] = { false };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == true)
{
printf("%d ", digit);
}
number[digit] = true;
n /= 10;
}
return 0;
}
But it will show the repeated digits again and again
(ex. input: 55544 output: 455)
I revised it:
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == 1)
{
printf("%d ", digit);
number[digit] = 2;
}
else if (number[digit] == 2)
break;
else number[digit] = 1;
n /= 10;
}
return 0;
}
It works!
However, I want to know how to do if I need to use boolean (true false), or some more efficient way?
To make your first version work, you'll need to keep track of two things:
Have you already seen this digit? (To detect duplicates)
Have you already printed it out? (To only output duplicates once)
So something like:
bool seen[10] = { false };
bool output[10] = { false };
// [...]
digit = ...;
if (seen[digit]) {
if (output[digit])) {
// duplicate, but we already printed it
} else {
// need to print it and set output to true
}
} else {
// set seen to true
}
(Once you've got that working, you can simplify the ifs. Only one is needed if you combine the two tests.)
Your second version is nearly there, but too complex. All you need to do is:
Add one to the counter for that digit every time you see it
Print the number only if the counter is exactly two.
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
// this is the second time we see this digit
// so print it out
}
n = ...;
Side benefit is that you get the count for each digit at the end.
Your second version code is not correct. You should yourself figured it out where are you wrong. You can try the below code to print the repeated elements.
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] > 0)
{
number[digit]++;;
}
else if (number[digit] ==0 )
number[digit] = 1;
n /= 10;
}
int i=0;
for(;i<10; i++){
if(number[i]>0)
printf("%d ", i);
}
return 0;
}
In case you want to print the repeated element using bool array (first version) then it will print the elements number of times elements occur-1 times and in reverse order because you are detaching the digits from the end of number , as you are seeing in your first version code output. In case you want to print only once then you have to use int array as in above code.
It is probably much easier to handle all the input as strings:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[256] = { 0 }; /* string to read */
char rep[256] = { 0 }; /* string to hold repeated digits */
int ri = 0; /* repeated digit index */
char *p = str; /* pointer to use with str */
printf ("\nEnter a number: ");
scanf ("%[^\n]s", str);
while (*p) /* for every character in string */
{
if (*(p + 1) && strchr (p + 1, *p)) /* test if remaining chars match */
if (!strchr(rep, *p)) /* test if already marked as dup */
rep[ri++] = *p; /* if not add it to string */
p++; /* increment pointer to next char */
}
printf ("\n Repeated digit(s): %s\n\n", rep);
return 0;
}
Note: you can also add a further test to limit to digits only with if (*p >= '0' && *p <= '9')
output:
$./bin/dupdigits
Enter a number: 1112223334566
Repeated digit(s): 1236
Error is here
if (number[digit] == true)
should be
if (number[digit] == false)
Eclipse + CDT plugin + stepping debug - help you next time
As everyone has given the solution: You can achieve this using the counting sort see here. Time complexity of solution will be O(n) and space complexity will be O(n+k) where k is the range in number.
However you can achieve the same by taking the XOR operation of each element with other and in case you got a XOR b as zero then its means the repeated number. But, the time complexity will be: O(n^2).
#include <stdio.h>
#define SIZE 10
main()
{
int num[SIZE] = {2,1,5,4,7,1,4,2,8,0};
int i=0, j=0;
for (i=0; i< SIZE; i++ ){
for (j=i+1; j< SIZE; j++){
if((num[i]^num[j]) == 0){
printf("Repeated element: %d\n", num[i]);
break;
}
}
}
}
main()
{
int prime_array[2339],prime1_count=0,mul1_count=0;
int i, prime, lim_up, lim_low, n,j=0;
int mul,count=0;
int mul_count[65026]={0},number[7096];
printf("\n ENTER THE LOWER LIMIT…: ");
scanf("%d", &lim_low);
printf("\n ENTER THE UPPER LIMIT…: ");
scanf("%d", &lim_up);
for(n=lim_low+1; n<lim_up; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
{
prime_array[j]=n;
j++;
}
}
for(i=1;i<=255;i++)
{
for(j=1;j<=255;j++)
{
mul = j*i;
mul_count[mul]++;
}
}
for(i=1;i<=65025;i++)
if( mul_count[i]!=2 && mul_count[i]!=0 )
{
number[count]=i;
count++;
}
for(prime1_count=0;prime1_count<2339;prime1_count++)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}
}
I want to find the modulus of (number[mul1_count] % prime_array[prime1_count] ), but the output which I get is wrong. What is the mistake here. The prime number should be in the range 40000 to 65025. What changes should i make here?
I don't really know what you are trying to do but when running your program I am getting a Floating Point Exception and thats because of the number[mul1_count] % prime_array[prime1_count] when prime_array[prime1_count] is 0
Wrap your inner for loop with an if(prime_array[prime1_count] != 0)
for(prime1_count=0;prime1_count<2339;prime1_count++)
{
if(prime_array[prime1_count] != 0)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}
}
It would be good to also try to explain what you want to do, what you expect, what you get, etc...
Edit :
Also, as a sidenote. You should slightly change the loop which calculates the prime numbers. The reason is that you do not keep track of how many prime numbers you calculated. and then you
for(prime1_count=0;prime1_count<2339;prime1_count++)
iterate through the whole prime_array[].
Imagine the situation where you only calculated 5 prime numbers, this means that the remaining array is left with whatever. No reason to do the extra calculation, leaving asside that the prime_array is not initialized to zero nowhere in the code which means it (afaik) contains garbage value, in the indeces where no prime number was allocated with your algorithm. This means that the
if(prime_array[prime1_count] != 0)
will probably fail if you think that garbage value exist there.
Either initialize the prime_array[2339] = { 0 };
OR
I would do that :
int number_of_primes=0;
for(n=lim_low+1; n<lim_up; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
{
if(number_of_primes < 2338)
{
prime_array[number_of_primes]=n;
number_of_primes++;
}else
{
break;
}
}
}
....
for(prime1_count=0 ; prime1_count < number_of_primes+1 ; prime1_count++)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}