Determine if a number is a prime without using loops and mutations? - c

How can I determine is a number is a prime without using a loop? I'm a beginner student and so far I've only been taught functional C. All I am allowed to use is the most basic code like + -, if, ==,!,||....Also, no variable mutations are allowed, all variables must be constant.
Here is my code with mutation:
bool prime(const int i, int a) {
if (a > i/2){
return false;
}
if (i%a == 0){
return true;
}
else {
return prime(i, a+1);
}
}
# int a is a counter its given initial value is always 2
#prime (5,2) --> false
#prime (9,2) --> true
However, as the question requires, no mutation is allowed, and only one variable is consumed so it should look like
bool prime(const int i) {
...
}
I'm thinking of a recursive approach but I just can't quite figure it out.
Also efficiency is not a factor to be considered in this problem.
Any help will be appreciated, thanks!

With an auxiliary function it should be more or less easy, although terrible innefficient:
bool prime(const int i)
{
prime_aux(i, i-1);
}
bool prime_aux(const int i, const int d)
{
if (d == 1) return true;
if (i % d == 0) return false;
return prime_aux(i, d - 1);
}
There are some easy optimizations out there, but I omitted them because the code is prettier this way. Also some checks to the input parameters may be needed before proceeding.

Only way I can think of is:
bool prime(const int i)
{
assert(i >= 0);
return char_array_odd_primes_const[i / 8] & (1U << (i % 8)) ? true : false;
}
Where char_array_primes_const contains 231 bits which are set to 1 for prime numbers and 0 for non-prime.
More efficient would be:
bool prime(const int i)
{
assert(i >= 0);
if(2 == i) return true;
if(i % 2) return false;
return char_array_primes_const[i / 16] & (1U << ((i/2) % 8)) ? true : false;
}

check a given number prime or not without loop,Recursion,Auxiliary Function
import java.math.RoundingMode;
import java.util.Scanner;
public class PrimeNumberwithoutloop {
static void PrimeNumber(double num)
{
double n=num/6;
if(n<Math.round(n))
{ n=6*(Math.round(n))-1;
if(n==num)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
else
{ n=6*(Math.round(n))+1;
if(n==num)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to check prime or not");
double num=sc.nextDouble();
PrimeNumber(num);
}
}

Randomized Algorithms are known to exist for determining whether a no. is prime or not (and most probably they use only a single input(i do not have idead regarding all such algorithms), i.e., the number itself that is to be tested for its primality). These algorithms are proven to be accurate in maximum no. of situations, i.e., the probability with which they can give the correct result is very high(although not 100% like the usual deterministic algorithms that are written). If you want, you can use them.
Refer to the following link for more details:
http://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests

This is the best possible way without using loop.
const isPrimeNumber = (num) => {
if(num % 2 === 0 || num % 3 === 0 || num % 5 === 0 || num % 7 === 0 || (Math.sqrt(num) - Math.floor(Math.sqrt(num))) === 0 ) {
console.log(`${num} = is not a prime number`)
}
else {
console.log(`${num} = is a prime number`)
}
}
isPrimeNumber(161);
isPrimeNumber(25689);
isPrimeNumber(11);

Related

Comparing both function on If and Else

Got this question just now when I’m tried comparing my program to both of my classmates (2 of them), and the results is there results came early (about 2 sec). Note that I forget to use the clock() function.
On if/else condition, is using the ternary operator
(Condition) ? (True) : (False);
slower than using this?
if (condition) {
(function if True)
}else {
(function if False)
}
There is no difference in terms of speed. Use ternary conditional only if you want to type less.
See the following example:
void f1(int i) {
int val = (i > 10) ? i * 5 : i * 10;
}
void f2(int i) {
int val;
if(i > 10){
val = i * 5;
}else{
val = i * 10;
}
}
See the compiler generated assembly for both the functions here.
There is no difference.

how to determine whether number is even or odd using each function?

typedef int bool;
bool even(int n)
{
return odd(n-1);
}
bool odd(int n)
{
return even(n-1);
}
I am having difficulty understanding this code in C
1.Please explain why this definition is wrong.
2.correct this code and make even and odd call each other.
Thank you!
If you manually trace this code, you will quickly see that the functions will call each other an infinite number of times. They will never return. They will just keep calling each other forever.
This will surely lead to a "Stack Overflow". Which is the error that this site gets its name from!
As you know these two functions call each other recursively, but there is no condition to stop the calling each other and it goes infinitely. Hence you can modify your code likes the following:
typedef int bool;
bool even(int n)
{
if(n == 0)
return 1;
if(n == 1)
return 0;
return odd(n-1);
}
bool odd(int n)
{
if(n == 1)
return 1;
if(n == 0)
return 0;
return even(n-1);
}
For example follow odd(2). Their call each other likes the following:
odd(2) -> even(1) -> return 0
Or odd(7):
odd(7) -> even(6) -> odd(5) -> even(4) -> odd(3) -> even(2) -> odd(1) -> return 1
Hence if passing an odd number to the odd function, these recursive calling finished by 1 on odd function and the same for even function and vice versa for passing odd or even number to even and odd respectively.
2.correct this code and make even and odd call each other.
To answer just #2
// Better to use standard types and includes.
// typedef int bool;
#include <stdbool.h>
// declare before use
bool odd(int n);
// At most 2 recursive calls.
bool even(int n) {
// return odd(n-1);
return (n < -1 || n > 1) ? !odd(n) : n==0;
}
bool odd(int n) {
// return even(n-1);
return !even(n%2);
}
For those concerned about high probability, n & 1 fails as an odd() test with the wrong answer for negative values on 1's complement machines rusting away in the big-iron heaven
bool isOdd( int num )
{
return( num & 1 );
}
bool isEven( int num )
{
return( !(num & 1) );
}
the code snippet
bool even(int n) {
return odd(n-1);
}
And
bool odd(int n) {
return even(n-1);
}
your calling even() & odd() recursively and there is no terminating condition which results in stack overflow.
to check whether given number is even or odd, you have to check 0th bit status, if 0th bit is zero means its even number, if 0th bit is one(1) means its odd number at one stage.
Instead of this you can use bitwise logic if at all recursion is not compulsory.
bool even(int n) {
return n & 1; /*bitwise And, in all odd number 0th bit is set(1) */
}
Or if you want to do using recursion then put the base condition. for e.g
typedef int bool;
bool even_odd_method(int n) {
if(n<2) {
return n%2;
}
return even_odd_method(n-2);
}
int main(void) {
int number;
printf("\n enter the number \n");
scanf("%d",&number);
number = number > 0 ? number : -number;/*if input no is negative */
int ret1 = even_odd_method(number);
if(ret1 == 0) {
printf("even \n");
}
else {
printf("odd \n");
}
return 0;
}

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

Display prime number

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)

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/

Resources