Display prime number - c

This programming I wrote below is used to display prime number from a list (20 numbers) which keyed in by user. But it only can detect 2 and 3 as prime number. I don't know why it doesn't work. Please tell me where is the errors and help me improve it. TQ.
#include <iostream>
#include <conio.h>
using namespace std;
void main ()
{
int i,number,list[20];
int t,p,prime=0;
cout<<"please key 20 numbers from 0 to 99"<<endl;
for(i=1;i<21;i++)
{
cin>>number;
if((number<0)||(number>99))
{
cout<<"Please key in an integer from 0 to 99"<<endl;
}
list[i]=number;
}
for(p=1;p<21;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if (prime==0&&list[p]!=1)
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
}
getch();
}

So there are a few issues with your code, but the one that will solve your issue is simply algorithmic.
When you start at the next iteration of p, you don't reset the value of prime and therefore it's always > 0 after we detect the second prime number and you'll never print out any again.
Change this:
for(p=1;p<21;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if (prime==0&&list[p]!=1)
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
}
To this (I've added some brackets for clairty and so we're certain the condition evaluates as we expect it to):
for(p=0;p<20;p++)
{
for(t=2;t<list[p];t++)
{
if ( list[p]%t==0)
{
prime=prime+1;
}
}
if ( (prime==0) && (list[p]!=1) )
{
cout<<"Prime numbers:"<<list[p]<<endl;
}
prime = 0;
}
And your issue will be solved.
HOWEVER: I would like to reiterate this does not solve all of your code issues. Make sure you think very carefully about the input part and what you are looping over (why is p 1 to 21? Why not 0 to 20 ;) arrays are zero indexed in C meaning that your list of 20 numbers goes from list[0] to list[19], you're currently looping from list[1] to list[20] which is actually out of range and I'm surprised you didn't get a segfault!)

What happens in your code is someone types in "123" or "-15"? Check and see if you can fix the error.
When you have fixed that, we can look at your prime checking code. Hint: there are a lot of prime testing code examples on the web.

Check this
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}

More Efficient Way
def print_hi(n):
if(n == 1 ):
return False;
if( n == 2 or n == 3):
return True;
if(n % 2 == 0 or n % 3 == 0):
return False;
for i in range (5,n,6):
if( i * i <= n):
if(n % i == 0 or n % (i+2) == 0):
return False
return True
if __name__ == '__main__':
x = print_hi(1032)
print(x)

Related

How do I generate 4 random variables and only printing if it doesn't contain the int 0

this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}

Coding bat beginner recursion

I am unable to find the logic for recursion in the problem mentioned below.
Given a non-negative int n, return the count of the occurrences of 7 as a digit
Eg. Count7(777)=3
Eg. Count7(123)=0
Eg. Count7(171)=1
Here is the logic that i applied
count number of 7 in ones place + count no of 7 in all the other place.
eg 13767
count number of 7 in (1)+ count number off 7 in (3767),just like factorial program where 5!=5*4!
count7(n)
{
if (n==0) {
return 0;
}
if (n==7) {
return 1;
}
if (n!=7) {
return 0;
}
return count7(n%10)+count7(n/10)
}
Any suggestion or help is appreciated .
You have
if (n==7) return 1;
followed by
if (n!=7) return 0;
As n is either 7 or not 7, everything that comes after will never be called. Instead you probably want
if (n<10) return 0;
as you want to call the recursion for numbers with more than 1 digit, and break here if you reached the last digit.
BTW, you could also remove the if (n==0) part, as this is also covered by the n<10.
The base case checks if there is just a single digit and if it is a 7 or not. Then, we recursively add the number of 7s in the remaining digits to whatever was found before (rem == 7 ? 1 : 0). This is just another bare-bones program. I am sure you can pick up from here.
#include <stdio.h>
int count7(int i)
{
int rem = i % 10; // remainder
int quo = i / 10; // quotient
if (rem == i) { // base case - check for a single digit.
if (rem == 7)
return 1;
else
return 0;
} else {
return (rem == 7 ? 1 : 0) + count7(quo);
}
}
int main(void) {
int i = 12;
printf("%d\n", count7(i));
}
The following code is completely functional.
#include<stdio.h>
void main()
{
printf("%d\n",count7(717));
}
int count7(int n)
{
if(n==7)
return 1;
else if(n<10)
return 0;
else
return count7(n%10)+count7(n/10);
}
There are some problems that I found in your code,
The critical problem is that you check if n!=7 and befor you check if n==7
that combination will equal to Ask the condition if() {} else {} that mean that in this case
you will not get to the next line - return count7(n%10)+count7(n/10) Never!!!!
Another thing that I saw is that you call at the return to count7 with the remainder of the number, it will work, but if you need to do a simple operation (check only if the remainder ==7 ) so my advice is to use to ? : condition and not to jump to function if you don't need.
My Code to your problem:
int count7(int n)
{
return n==0 ? 0 : (n==7 ? 1 : count7(n/10) + (n%10 == 7 ? 1 : 0) );
}
And another code more readably (do the same work) :
int count7(int curNum)
{
int curModNum=n%10;
int curDivNum=n/10;
if (currentNum==EMPTY_NUM) {
return EMPTY_NUM;
}
if (curNum==LUCKY_NUM) {
return ADD_ONE;
}
return count7(curDivNum) + (curModNum == LUCKY_NUM ? ADD_ONE : EMPTY_NUM);
}

How to find occurences of a digit with 4 in it within 50?

I want to know how to find the number of times that 4 occurs within a certain range; lets say 50 for example.
Therefore if the input is the range 50, then output should look like
4,14,24,34,40,41,...,49.
Now its pretty easy to find the first half of the output that is 4,14,..so on,i.e digits ending with 4,
for(i=0;i<=50;i++)
if(i%10==4)
{
printf("%d",i);
}
but what about starting with 4? Can the problem be solved using regular expressions?
You could try to use a function that repeatedly tests each digit in the number to see if it is equal to 4, like so:
int check4(int x)
{
//Units place
if (x==0)
{
return 0;
}
else if (x%10 == 4)
{
return 1;
}
//Divide by 10 so that tens place is now unit place; repeat till no more tens place
else
{
return check4(x/10);
}
}
This solution completely eschews the need for string processing.
Demo
No need for regex at all. Store the integer as a string in temporary variable, and then use strstr.
for( i = 0; i <= input; i++ ) {
char str[20];
sprintf( str, "%d", i );
if( strstr(str, "4") )
printf( "%d ", i );
}
Here's a demo on codepad.
The idea is simple: check the ending digit to see if it is 4, if not, keep dividing the number by 10 until the last digit is 4, or the number is 0.
It is equally easy to do in iterative or recursive approach:
Pseudo code (Iterative):
boolean contains4(int input) {
while (input > 0) {
if (i % 10 == 4) {
return true;
}
input /= 10;
}
return false;
}
Pseudo-code (Recursive):
boolean contains4(int input) {
if (input == 0) {
return false;
} else if (input % 10 == 4) {
return true;
} else {
return contains4(input / 10);
}
}

Number of Trailing Zeros in a Factorial in c

I am new to C programming
I want to find out the number of trailing zeros in a Factorial of given number
{
long int n=0,facto=1,ln=0;
int zcount=0,i=1;
printf("Enter a number:");
scanf("%ld",&n);
if(n==0)
{
facto=1;
}
else
{
for(i=1;i<=n;i++)
{
facto=facto*i;
}
}
printf("%ld",facto);
while(facto>0)
{
ln=facto%10;
facto/10;
if(ln=!0)
{
break;
}
else
{
zcount+=1;
}
}
printf("Tere are Total %d Trailing zeros in given factorial",zcount);
}
I have tried to calculate the modulo of the the number which will return the last digit of given number as the remainder and then n/10; will remove the last number.
After executing the program the output always shows number of trailing zeros as "0",The condition if(ln =! 0) always gets satisfied even if there is a zero.
Let us remember math (wiki):
int trailingZeroCountInFactorial(int n)
{
int result = 0;
for (int i = 5; i <= n; i *= 5)
{
result += n / i;
if(i > INT_MAX / 5) // prevent integer overflow
break;
}
return result;
}
This
if(ln=!0)
means ln = !0 i.e. you are assigning !0 to ln so the condition is always true, change it to
if (ln != 0)
you can use an assignment as a truth value, but if you are sure you are doing it.
To prevent accidentally doing it, turn on compiler warnings.
The correct syntax in
if(ln!=0)
{
// do something
}
In if ( ln=!0 ) , first !0 is evaluated then = assigns !0(which is 1) to ln, then if checks the value of ln, if the value is non-zero(in this case it is 1 due to previous assignment) then break statement is executed.
Also, this approach will not work for numbers larger than 25.
It is obvious that the power of 5 in n! will be the answer.
The following expression gives the power of a prime p in n! :-
f(n/p) + f(n/p^2) + f(n/p^3) + ..... (until f(n/p^k) return zero, where f(a) returns the greatest integer of a or the floor of a
package lb;
import java.util.Scanner;
public class l1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a=n/5;
if(a<5)
{
System.out.println(a);
}
else
{
int c=a/5+a;
System.out.println(c);
}
}
}
Try this
int trailingZeroCountInFactorial(int n)
{
int result = 0;
for (int i = 5; i <= n; i *= 5)
{
result += n / i;
}
return result;
}
To learn, how it works, there is a great explanation here
I have solved this kind of problem, I think your question is just find the number of trailing zeros of a factorial number like - 15! = 1307674368000 if you look at the trailing 3 digits which are 000 Efficient code is
int n;cin>>n;
int ans = 0;
while(n)
{ ans += (n = n/5);}
cout<<ans;
Here one should look for int overflow, array bounds. Also, the special cases are n=1?
{
long int n=0,facto=1,ln=0;
int zcount=0,i=1;
printf("Enter a number:");
scanf("%ld",&n);
if(n==0)
{
facto=1;
}
else
{
for(i=1;i<=n;i++)
{
facto=facto*i;
}
}
printf("%ld\n",facto);
while(facto>0)
{
ln=(facto%10);
facto/=10; //here you done one mistake
if(ln!=0) //another one here
{
break;
}
else
{
zcount+=1;
}
}
printf("Tere are Total %d Trailing zeros in given factorial",zcount);
}
/Run this code it will work now and mistakes you already knows i guess/

I would like to to generate random values in C

I would like to ask about random values in C.
My C program has coding as below.
int random_a( int current_s,int r[num_s][num_a])
{
int i;
for(i=0;i<4;i++)
{
if(r[current_s][i] > -1) break;
}
return i;
}
For example condition
r[current_s][0] and r[current_s][2] > -1
If I run my program, answer have only i = 0. But I would like to get random answer that is 0 and 2 (1 and 3 not included because r[current_s][1] and r[current_s][3] = -1).
As my plan, I would like to get a random value between 0 and 3 using (rand()%4); if (r[current_s][i] > -1) is correct I will return that value. But if (r[current_s][i] = -1) generate a random number again until r[current_s][i] > -1 then return value.
What should I do?
Assuming that current_s is the row number of your matrix which contains the values -1 or greater, you can use this code :
int random_a(int current_a, int r[num_s][num_a])
{
if (current_a>num_s) return 0; //checking condition as current_a changes below
int i;
for (i=0;i<4;i++)
{
if(r[current_s][i] > -1) return i;
else if (r[current_s][i] && i==3) return (random_a(current_a+1,r[num_s][num_a])
else i++;
}
}
here you can change current_a based on your need.

Resources