Reaching the number 42 by recursion - c++

I am trying to create a bear game where the user enters a number (n), and the program will see if it can reach the number 42 by doing some specified steps. If it can't, then it notifies the user that number can't reach the goal.
These are the rules:
If n is even, then you may give back exactly n/2 bears.
If n is divisible by 3 or 4, then you may multiply the last two digits of n and give back this
many bears.
If n is divisible by 5, then you may give back exactly 42 bears.
Here's an example:
Start with 250 bears
Since 250 is divisible by 5, you may return 42 of the bears, leaving you with 208 bears.
Since 208 is even, you may return half of the bears, leaving you with 104 bears.
Since 104 is even, you may return half of the bears, leaving you with 52 bears.
Since 52 is divisible by 4, you may multiply the last two digits (resulting in 10) and return
these 10 bears. This leaves you with 42 bears.
You have reached the goal!
Here's what I have so far:
#include <iostream>
using namespace std;
bool bears(int n);
int main(){
int number;
do{
cout<<"enter the amount of bears (press 0 to stop the program): ";
cin>>number;
if (bears(number)){
cout<<"you have reached the goal!"<<endl;
}
else{
cout<<"sorry, you have not reached the goal."<<endl;
}
}while(number != 0);
}
bool bears(int n){
if (n < 42){
return false;
}
else if (n == 42){
return true;
}
else{
if (n % 5 == 0){
return bears(n - 42);
}
else if(n % 2 == 0){
return bears(n / 2);
}
else if(n % 4 == 0|| n % 3 == 0)
{
int one;
int two;
one=n%10;
two=(n%100)/10;
return bears(n - one * two);
}
}
}
My program has the basic rules, but when I type in 250 bears it says it can't reach the goal. I understand what's happening in the code and why it can't reach the specified goal, but how do I make it universal so it'll work not just for the number 250, but for other numbers like: 84.

#Corristo's answer is good, but a similar depth first search algorithm can be used with minimal changes to your code. I've removed the redundant ifs and elses (since we're returning in every condition).
What this function does is instead of using a greedy approach like your solution does, it tests all cases till it finds an answer. Your code tests the second condition only if the first condition (divisibility by 5) is not satisfied, and so on.
bool bears(int n){
if (n < 42)
return false;
if (n == 42)
return true;
// Moves on if condition isn't satisfied
if ((n % 5 == 0) && bears(n - 42)) return true;
if ((n % 2 == 0) && bears(n / 2)) return true;
if(n % 4 == 0|| n % 3 == 0)
{
int one;
int two;
one=n%10;
two=(n%100)/10;
return one * two != 0 && bears(n - one * two);
}
return false;
}
You can try optimizing it further by using a cache (std::map) where you store the results and return the stored result if you have computed it before, but it'll only help in very few cases.

Since we don't have any a priori knowledge about which rule we need to choose for a particular number, the easiest way is to try all of them by exploring the entire state space. You can think of it as a reachability problem in an implicitly given graph.
One way to solve such a reachability problem is by using breath-first or depth-first search, which can be implemented recursively.
For your game this can be done by modifying your bears function to take a std::vector of integers for which it checks if it contains at least one number from which 42 can be reached.
With a depth-first search it might look as follows:
bool bears(std::vector<int> ns) {
// first remove all numbers < 42 since the goal cannot be reached from them
ns.erase(std::remove_if(std::begin(ns), std::end(ns),
[] (auto const& n) { return n < 42; }),
std::end(ns));
if (ns.empty()) {
return false;
} else if (std::any_of(std::cbegin(ns),
std::cend(ns),
[] (auto const& n) { return n == 42; })) {
return true;
} else {
auto possible_number_of_bears = std::vector<std::vector<int>>{};
std::transform(std::cbegin(ns),
std::cend(ns),
std::back_inserter(possible_number_of_bears),
[] (auto const& n) {
auto after_possible_rules = std::vector<int>{};
if (n % 5 == 0) {
after_possible_rules.emplace_back(n - 42);
}
if (n % 2 == 0) {
after_possible_rules.emplace_back(n / 2);
}
if (n % 4 == 0 || n % 3 == 0) {
int one;
int two;
one = n % 10;
two = (n % 100) / 10;
// avoid infinite recursion by only adding
// the new number if it is different from n
if (one * two != 0) {
after_possible_rules.emplace_back(n - one * two);
}
}
return after_possible_rules; });
return std::any_of(std::cbegin(possible_number_of_bears),
std::cend(possible_number_of_bears),
bears);
}
}
Now you only need to adjust the calling code to
if (bears({number})) {
std::cout << "you have reached the goal!" << std::endl;
} else {
std::cout << "sorry, you have not reached the goal." << std::endl;
}
and modify the forward declaration of bears accordingly.

Related

How to minimize the times a recursive function is called

So for the following code I am trying to reduce the amount of time the function call itself so that it is more efficient. The purpose of the code is to perform exponentiation using recursion.
int expo(const int m, const unsigned int n)
{
funcCallCounter++; //counts how many times the function is called
if (n == 0)//base case
{
return 1;
}
else if (n % 2 == 0)// for even numbers
return expo(m*m, n / 2);
else
return m * expo(m, n - 1);//for odd numbers
}
Well this is my favourite approach for the recursive expo which will always give less calls than your approach
int expo(int a, int n) {
funcCallCounter++;
if (n == 0) {
return 1;
}
int r = expo(a, n / 2);
if (n % 2 == 0) {
//Even n
return r * r;
}
else {
// Odd n
return a *r*r;
}
}
You could use shifts to make your execution faster.
n % 2 can be replaced with n & 0x01
n / 2^k can be replaced with n >> k
A division is about 20 cycles while a shift is only 1-2 cycles.
However, maybe the compiler see taht by itself and make this optimisation already.
Best

Can someone thoroughly explain this IsItPrime Function?

This is the function I found on CodeReview site, it determines if a number is a prime, while also handling negative numbers. There are few things I can't really catch up with.
1) Why is the first condition <= 3 when it's supposed to deal with negatives?
2) What does return n > 1 actually returns? And does it, in any way, affect other conditions?
bool IsItPrime(int n)
{
if(n <= 3) {
return n > 1;
} else if(n % 2 == 0 || n % 3 == 0) {
return false;
} else {
for(int i(5); i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}
if(n <= 3) {
return n > 1;
}
Is clever if not the easiest thing to reason out. First you enter the if body if you have a number of 3 or less. This covers the first 2 prime numbers plus all negative numbers, 0, and 1. Then it goes on to return n > 1; this means that if n is greater than 1 you will return true, otherwise false. So, if n is 2 or 3 the function will return true. It is is less than 2 then it returns false. It would be the same as
if (n <= 1) return false;
else if (n == 2 || n == 3) return true
else if ...
But as you can see that is more typing and adds an if statement.
according to wikipedia:
A prime number (or a prime) is a natural number greater than 1
return n > 1 means return true for any number greater than 1, (i.e. 2 or 3, because this appears after the test if n<=3). 0, 1 or a negative number will make it return false.
1) Why is the first condition <= 3 when it's supposed to deal with
negatives? 2) What does return n > 1 actually returns?
These questions are linked:
The function can take a negative argument, but as you can see the first set of conditions tests if the argument is between 1 and 3. 2,3 being prime, it will return true, if the argument is 1,0 or negative, it will return false (so it doesn't really work with negative numbers).
if(n <= 3) {
return n > 1;
}
This will return false for all numbers less than or equal to 3, except for 2 and 3. This handles negative numbers as well (any negative number will be less than 3).
else if(n % 2 == 0 || n % 3 == 0) {
return false;
}
This does a modulus operation on your argument, and returns false if the number is divisible by 2 or 3 (which would also make it not prime). We're safe to call this even though 2 and 3 are divisible since they're are handled above.
else {
for(int i(5); i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
This handles all other digits by looping until you're above the square root of a number. It also does modulus operations, this time with 5, 7, and all values n + 6, n + 8 (<11, 13>, <17, 19>, etc). We can iterate by 6 since we're doing the 2 and 3 modulus operations above.

Counting numbers that have three different prime factors

There are 1000 numbers in numbers.txt, 2 to 9 digits each, each in a seperate line. The exercise is tocount how many numbers there are, that fullfill the condition: when factorized, this number has exactly 3 different prime factors, they can occur several times and they all are even numbers.
for example
105 - factors: 3, 5 ,7 - YES,
1287 - factors: 3, 3, 11, 13 - YES,
1157625 - factors: 3,3,3,5,5,5,7,7,7 - YES,
55 - factors: 5, 11 - NO.
#include <iostream>
#include <fstream>
using namespace std;
int number, threefnumbers=0;
int main()
{
ifstream file("numbers.txt");
ofstream outputf("results.txt");
int count_factors;
while (file >> number)
{
count_factors=0;
int factor=3;
if (number%2!=0)
{
while (number>1)
{
if (number%factor==0)
count_factors++;
while (number%factor==0)
{
number=number/factor;
}
factor+=2;
}
if (count_factors==3) threefnumbers++;
}
}
outputf << "59.1) " << endl << threefnumbers;
file.close();
outputf.close();
return 0;
}
I know from the numbers.txt, that there are many numbers that fulfill the condition, but the program returns only 1. Why so?
Your code ignores the fact that 2 is a prime number. You need to check if the number read in can be reduced by 2. You could do that with something that look like:
while(read number)
{
int factor_count = 0;
// check 2 by itself
if (number % 2 == 0)
{
factor_count++;
while(number % 2 == 0)
number /= 2;
}
for (int factor = 3; factor < number; factor += 2)
{
if (number % factor == 0)
{
factor_count++;
while(number % factor == 0)
number /= factor;
}
}
if(factor_count == 3)
do something
}
This entire thing could be made more efficient by making a list of prime numbers that goes up to the max number possible in the file which in this case would be 999,999,999. Then you can just iterate through that prime number list until you run out of prime factors. That would look something like
std::vector<int> primes = get_prime_list(999999999);
// returns a list of all prime numbers less than the number passed in.
// leaving it to you to implement but a Sieve of Eratosthenes should work well
while(read number)
{
int factor_count = 0;
for(auto e : primes)
{
if (number % e == 0)
{
factor_count++;
while(number % e == 0)
number /= e;
}
if (number == 1) // number is fully factorized
break;
}
if(factor_count == 3)
do something
}

C++ Prime Number Program not recognizing 3? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My program is supposed to detect prime numbers from 1 to 100 and save them to a file.
For some reason, it does not recognize 3 but mistakenly recognizes some multiples (27, 33, etc) of 3 as prime.
Code follows...
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
// check for 2, a prime number that will not be caught by for loop algorithm
if (test == 2)
{
prime = true;
}
// eliminate all even numbers other than 2
else if ( test%2 == 0)
{
prime = false;
}
// eliminate 0
else if ( test == 0)
{
prime = false;
}
//eliminate 1, which is not prime or composite
else if ( test == 1)
{
prime = false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
}
if (prime == true)
{
cout << "The number " <<test << " is prime." <<endl;
}
return prime;
EDIT for code fix:
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
double sqrt_num = sqrt(test);
//check for number 2 which algorithm wont catch, but is prime
if (test ==2)
{
return true;
}
// check if even and return false
else if ( test% 2 == 0)
{
return false;
}
//eliminate 1, which is not prime or composite, and 0.
else if ( test == 0 || test == 1)
{
return false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 3; i <= sqrt_num;i+=2)
{
if (test%i == 0)
{
return false;
}
}
}
return true;
}
The biggest error in your code is your for-loop:
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
If we step through if for your false test cases 3 and 27, we see that for 3 it is this:
for (int i = 1; i <= 1; i++)
{
if (3 % 1 == 0)
{
prime = false;
}
else if (3 % 1 != 0)
{
prime = true;
}
}
The loop will be computed once, and the result (false) returned. The reason for this is that your loop starts with 1 and because every number is divisible by 1, every number which is only checked for 1 will always be composite. To fix this we just start with the number 2. If we do this, we have to set an initial value for "prime" because otherwise we would return a null value. Our initial value will be true, which means every number is prime until proven otherwise which, conveniently, is exactly what our for loop does.
The second error occurs when you reach the last iteration of the loop for 27:
//i == 5
for (int i = 1; i <= 5; i++)
{
if (27 % 5 == 0)
{
prime = false;
}
else if (27 % 5 != 0)
{
prime = true;
}
}
Because the last iteration sets prime to true, true is returned, which is obviously false. A possible solution is to exit the loop if we encounter an i for which number % i == 0 holds, as this means we have found a valid factor for said number.
TL; DR: Solving the errors we got:
start with the number 2 instead of one to get rid of the corner case 3 (and 2 as well)
if a valid factor is found the number is definitely composite and we set prime to false and exit the loop because we found a result.
Using the fixes and simplifying we get:
bool isPrime(int number)
{
// special cases 0 and 1
if (i == 0 || i == 1)
{
return false;
}
// else check from i = 2 to sqrt(number) if any of them divides the number
// if yes, the number is not prime and it returns false.
for (int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
// if the number is not 0 or 1 and has passed the loop, it must be prime,
// hence we can return true
return true;
}
A small optimisation to make would be checking if it is even and if not just testing division by odd numbers. We would then replace the for-loop by:
if (number % 2 == 0)
{
return false;
}
for (int i = 3; i <= sqrt(number); i=i+2)
{
if (number % i == 0)
{
return false;
}
}
(int)sqrt(3) is 1, every test%1 will return 0 because division by 1 has no remainder.
You should stop the loop once you find proof that the number is not prime. If you keep it going the result will be misleading.
Note: sqrt() is an expensive function. Consider saving its result in a variable so you don't have to run it every loop.
Since you start the loop with i = 1, the condition test%i == 0 is always true.
So you should start it with i = 2, which will allow you to test numbers greater than or equal to 4.
In addition, you should break the loop once you set prime = false.
You will have to test 3 separately, since 2 > sqrt(3).
A few suggestions for improvement:
bool isPrime(int number)
{
// Handle 0 and 1
if (number < 2)
return false;
// Handle 2 and 3
if (number < 4)
return true;
// Handle numbers that are not adjacent to a multiple of 6
if (number%2==0 || number%3==0)
return false;
// Calculate once
int root = (int)sqrt(number);
// Check divisibility by numbers that are equal to -1(mod6)
for (int i=5; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
// Check divisibility by numbers that are equal to +1(mod6)
for (int i=7; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
return true;
}

Determining if a number is prime

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks whether the given input number is prime.
Here is what I was able to write, but it does not work:
void primenumber(int number)
{
if(number%2!=0)
cout<<"Number is prime:"<<endl;
else
cout<<"number is NOt prime"<<endl;
}
I would appreciate if someone could give me advice on how to make this work properly.
Update
I modified it to check on all the numbers in a for loop.
void primenumber(int number)
{
for(int i=1; i<number; i++)
{
if(number%i!=0)
cout<<"Number is prime:"<<endl;
else
cout<<"number is NOt prime"<<endl;
}
}
bool isPrime(int number){
if(number < 2) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ) return false;
}
return true;
}
My own IsPrime() function, written and based on the deterministic variant of the famous Rabin-Miller algorithm, combined with optimized step brute forcing, giving you one of the fastest prime testing functions out there.
__int64 power(int a, int n, int mod)
{
__int64 power=a,result=1;
while(n)
{
if(n&1)
result=(result*power)%mod;
power=(power*power)%mod;
n>>=1;
}
return result;
}
bool witness(int a, int n)
{
int t,u,i;
__int64 prev,curr;
u=n/2;
t=1;
while(!(u&1))
{
u/=2;
++t;
}
prev=power(a,u,n);
for(i=1;i<=t;++i)
{
curr=(prev*prev)%n;
if((curr==1)&&(prev!=1)&&(prev!=n-1))
return true;
prev=curr;
}
if(curr!=1)
return true;
return false;
}
inline bool IsPrime( int number )
{
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
return (false);
if(number<1373653)
{
for( int k = 1; 36*k*k-12*k < number;++k)
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
return (false);
return true;
}
if(number < 9080191)
{
if(witness(31,number)) return false;
if(witness(73,number)) return false;
return true;
}
if(witness(2,number)) return false;
if(witness(7,number)) return false;
if(witness(61,number)) return false;
return true;
/*WARNING: Algorithm deterministic only for numbers < 4,759,123,141 (unsigned int's max is 4294967296)
if n < 1,373,653, it is enough to test a = 2 and 3.
if n < 9,080,191, it is enough to test a = 31 and 73.
if n < 4,759,123,141, it is enough to test a = 2, 7, and 61.
if n < 2,152,302,898,747, it is enough to test a = 2, 3, 5, 7, and 11.
if n < 3,474,749,660,383, it is enough to test a = 2, 3, 5, 7, 11, and 13.
if n < 341,550,071,728,321, it is enough to test a = 2, 3, 5, 7, 11, 13, and 17.*/
}
To use, copy and paste the code into the top of your program. Call it, and it returns a BOOL value, either true or false.
if(IsPrime(number))
{
cout << "It's prime";
}
else
{
cout<<"It's composite";
}
If you get a problem compiling with "__int64", replace that with "long". It compiles fine under VS2008 and VS2010.
How it works:
There are three parts to the function. Part checks to see if it is one of the rare exceptions (negative numbers, 1), and intercepts the running of the program.
Part two starts if the number is smaller than 1373653, which is the theoretically number where the Rabin Miller algorithm will beat my optimized brute force function. Then comes two levels of Rabin Miller, designed to minimize the number of witnesses needed. As most numbers that you'll be testing are under 4 billion, the probabilistic Rabin-Miller algorithm can be made deterministic by checking witnesses 2, 7, and 61. If you need to go over the 4 billion cap, you will need a large number library, and apply a modulus or bit shift modification to the power() function.
If you insist on a brute force method, here is just my optimized brute force IsPrime() function:
inline bool IsPrime( int number )
{
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
return (false);
for( int k = 1; 36*k*k-12*k < number;++k)
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
return (false);
return true;
}
}
How this brute force piece works:
All prime numbers (except 2 and 3) can be expressed in the form 6k+1 or 6k-1, where k is a positive whole number. This code uses this fact, and tests all numbers in the form of 6k+1 or 6k-1 less than the square root of the number in question. This piece is integrated into my larger IsPrime() function (the function shown first).
If you need to find all the prime numbers below a number, find all the prime numbers below 1000, look into the Sieve of Eratosthenes. Another favorite of mine.
As an additional note, I would love to see anyone implement the Eliptical Curve Method algorithm, been wanting to see that implemented in C++ for a while now, I lost my implementation of it. Theoretically, it's even faster than the deterministic Rabin Miller algorithm I implemented, although I'm not sure if that's true for numbers under 4 billion.
You need to do some more checking. Right now, you are only checking if the number is divisible by 2. Do the same for 2, 3, 4, 5, 6, ... up to number. Hint: use a loop.
After you resolve this, try looking for optimizations.
Hint: You only have to check all numbers up to the square root of the number
I would guess taking sqrt and running foreach frpm 2 to sqrt+1 if(input% number!=0) return false;
once you reach sqrt+1 you can be sure its prime.
C++
bool isPrime(int number){
if (number != 2){
if (number < 2 || number % 2 == 0) {
return false;
}
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ){
return false;
}
}
}
return true;
}
Javascript
function isPrime(number)
{
if (number !== 2) {
if (number < 2 || number % 2 === 0) {
return false;
}
for (var i=3; (i*i)<=number; i+=2)
{
if (number % 2 === 0){
return false;
}
}
}
return true;
}
Python
def isPrime(number):
if (number != 2):
if (number < 2 or number % 2 == 0):
return False
i = 3
while (i*i) <= number:
if(number % i == 0 ):
return False;
i += 2
return True;
If you know the range of the inputs (which you do since your function takes an int), you can precompute a table of primes less than or equal to the square root of the max input (2^31-1 in this case), and then test for divisibility by each prime in the table less than or equal to the square root of the number given.
This code only checks if the number is divisible by two. For a number to be prime, it must not be evenly divisible by all integers less than itself. This can be naively implemented by checking if it is divisible by all integers less than floor(sqrt(n)) in a loop. If you are interested, there are a number of much faster algorithms in existence.
If you are lazy, and have a lot of RAM, create a sieve of Eratosthenes which is practically a giant array from which you kicked all numbers that are not prime.
From then on every prime "probability" test will be super quick.
The upper limit for this solution for fast results is the amount of you RAM. The upper limit for this solution for superslow results is your hard disk's capacity.
I follow same algorithm but different implementation that loop to sqrt(n) with step 2 only odd numbers because I check that if it is divisible by 2 or 2*k it is false. Here is my code
public class PrimeTest {
public static boolean isPrime(int i) {
if (i < 2) {
return false;
} else if (i % 2 == 0 && i != 2) {
return false;
} else {
for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
}
/**
* #param args
*/
public static void main(String[] args) {
for (int i = 1; i < 100; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
}
Use mathematics first find square root of number then start loop till the number ends which you get after square rooting.
check for each value whether the given number is divisible by the iterating value .if any value divides the given number then it is not a prime number otherwise prime.
Here is the code
bool is_Prime(int n)
{
int square_root = sqrt(n); // use math.h
int toggle = 1;
for(int i = 2; i <= square_root; i++)
{
if(n%i==0)
{
toggle = 0;
break;
}
}
if(toggle)
return true;
else
return false;
}
bool check_prime(int num) {
for (int i = num - 1; i > 1; i--) {
if ((num % i) == 0)
return false;
}
return true;
}
checks for any number if its a prime number
Someone had the following.
bool check_prime(int num) {
for (int i = num - 1; i > 1; i--) {
if ((num % i) == 0)
return false;
}
return true;
}
This mostly worked. I just tested it in Visual Studio 2017. It would say that anything less than 2 was also prime (so 1, 0, -1, etc.)
Here is a slight modification to correct this.
bool check_prime(int number)
{
if (number > 1)
{
for (int i = number - 1; i > 1; i--)
{
if ((number % i) == 0)
return false;
}
return true;
}
return false;
}
Count by 6 for better speed:
bool isPrime(int n)
{
if(n==1) return false;
if(n==2 || n==3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5; i*i<=n; i=i+6)
if(n%i==0 || n%(i+2)==0)
return false;
return true;
}
There are several different approches to this problem.
The "Naive" Method: Try all (odd) numbers up to (the root of) the number.
Improved "Naive" Method: Only try every 6n ± 1.
Probabilistic tests: Miller-Rabin, Solovay-Strasse, etc.
Which approach suits you depends and what you are doing with the prime.
You should atleast read up on Primality Testing.
If n is 2, it's prime.
If n is 1, it's not prime.
If n is even, it's not prime.
If n is odd, bigger than 2, we must check all odd numbers 3..sqrt(n)+1, if any of this numbers can divide n, n is not prime, else, n is prime.
For better performance i recommend sieve of eratosthenes.
Here is the code sample:
bool is_prime(int n)
{
if (n == 2) return true;
if (n == 1 || n % 2 == 0) return false;
for (int i = 3; i*i < n+1; i += 2) {
if (n % i == 0) return false;
}
return true;
}
I came up with this:
int counter = 0;
bool checkPrime(int x) {
for (int y = x; y > 0; y--){
if (x%y == 0) {
counter++;
}
}
if (counter == 2) {
counter = 0; //resets counter for next input
return true; //if its only divisible by two numbers (itself and one) its a prime
}
else counter = 0;
return false;
}
This is a quick efficient one:
bool isPrimeNumber(int n) {
int divider = 2;
while (n % divider != 0) {
divider++;
}
if (n == divider) {
return true;
}
else {
return false;
}
}
It will start finding a divisible number of n, starting by 2. As soon as it finds one, if that number is equal to n then it's prime, otherwise it's not.
//simple function to determine if a number is a prime number
//to state if it is a prime number
#include <iostream>
using namespace std;
int isPrime(int x); //functioned defined after int main()
int main() {
int y;
cout << "enter value" << endl;
cin >> y;
isPrime(y);
return 0;
} //end of main function
//-------------function
int isPrime(int x) {
int counter = 0;
cout << "factors of " << x << " are " << "\n\n"; //print factors of the number
for (int i = 0; i <= x; i++)
{
for (int j = 0; j <= x; j++)
{
if (i * j == x) //check if the number has multiples;
{
cout << i << " , "; //output provided for the reader to see the
// muliples
++counter; //counts the number of factors
}
}
}
cout << "\n\n";
if (counter > 2) {
cout << "value is not a prime number" << "\n\n";
}
if (counter <= 2) {
cout << "value is a prime number" << endl;
}
}
Here is a simple program to check whether a number is prime or not:
#include <iostream>
using namespace std;
int main()
{
int n, i, m=0, flag=0;
cout << "Enter the Number to check Prime: ";
cin >> n;
m=n/2;
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
cout<<"Number is not Prime."<<endl;
flag=1;
break;
}
}
if (flag==0)
cout << "Number is Prime."<<endl;
return 0;
}
Here is a C++ code to determine that a given number is prime:
bool isPrime(int num)
{
if(num < 2) return false;
for(int i = 2; i <= sqrt(num); i++)
if(num % i == 0) return false;
return true;
}
PS Don't forget to include math.h library to use sqrt function
well crafted, share it with you:
bool isPrime(int num) {
if (num == 2) return true;
if (num < 2) return false;
if (num % 2 == 0) return false;
for (int i = num - 1; i > 1; i--) {
if (num % i == 0) return false;
}
return true;
}
There are many potential optimization in prime number testing.
Yet many answers here, not only are worse the O(sqrt(n)), they suffer from undefined behavior (UB) and incorrect functionality.
A simple prime test:
// Return true when number is a prime.
bool is_prime(int number) {
// Take care of even values, it is only a bit test.
if (number % 2 == 0) {
return number == 2;
}
// Loop from 3 to square root (n)
for (int test_factor = 3; test_factor <= number / test_factor; test_factor +=
2) {
if (number % test_factor == 0) {
return false;
}
}
return n > 1;
}
Do not use test_factor * test_factor <= number. It risks signed integer overflow (UB) for large primes.
Good compilers see nearby number/test_factor and number % test_factor and emit code that computes both for the about the time cost of one. If still concerned, consider div().
Avoid sqrt(n). Weak floating point libraries do not perform this as exactly as we need for this integer problem, possible returning a value just ever so less than an expected whole number. If still interested in a sqrt(), use lround(sqrt(n)) once before the loop.
Avoid sqrt(n) with wide integer types of n. Conversion of n to a double may lose precision. long double may fair no better.
Test to insure the prime test code does not behave poorly or incorrectly with 1, 0 or any negative value.
Consider bool is_prime(unsigned number) or bool is_prime(uintmax_t number) for extended range.
Avoid testing with candidate factors above the square root n and less than n. Such test factors are never factors of n. Not adhering to this makes for slow code.
A factor is more likely a small value that an large one. Testing small values first is generally far more efficient for non-primes.
Pedantic: Avoid if (number & 1 == 0) {. It is an incorrect test when number < 0 and encoded with rare ones' complement. Use if (number % 2 == 0) { and trust your compiler to emit good code.
More advanced techniques use a list of known/discovered primes and the Sieve of Eratosthenes.
#define TRUE 1
#define FALSE -1
int main()
{
/* Local variables declaration */
int num = 0;
int result = 0;
/* Getting number from user for which max prime quadruplet value is
to be found */
printf("\nEnter the number :");
scanf("%d", &num);
result = Is_Prime( num );
/* Printing the result to standard output */
if (TRUE == result)
printf("\n%d is a prime number\n", num);
else
printf("\n%d is not a prime number\n", num);
return 0;
}
int Is_Prime( int num )
{
int i = 0;
/* Checking whether number is negative. If num is negative, making
it positive */
if( 0 > num )
num = -num;
/* Checking whether number is less than 2 */
if( 2 > num )
return FALSE;
/* Checking if number is 2 */
if( 2 == num )
return TRUE;
/* Checking whether number is even. Even numbers
are not prime numbers */
if( 0 == ( num % 2 ))
return FALSE;
/* Checking whether the number is divisible by a smaller number
1 += 2, is done to skip checking divisibility by even numbers.
Iteration reduced to half */
for( i = 3; i < num; i += 2 )
if( 0 == ( num % i ))
/* Number is divisible by some smaller number,
hence not a prime number */
return FALSE;
return TRUE;
}
I Have Use This Idea For Finding If The No. Is Prime or Not:
#include <conio.h>
#include <iostream>
using namespace std;
int main() {
int x, a;
cout << "Enter The No. :";
cin >> x;
int prime(unsigned int);
a = prime(x);
if (a == 1)
cout << "It Is A Prime No." << endl;
else
if (a == 0)
cout << "It Is Composite No." << endl;
getch();
}
int prime(unsigned int x) {
if (x == 1) {
cout << "It Is Neither Prime Nor Composite";
return 2;
}
if (x == 2 || x == 3 || x == 5 || x == 7)
return 1;
if (x % 2 != 0 && x % 3 != 0 && x % 5 != 0 && x % 7 != 0)
return 1;
else
return 0;
}
if(number%2!=0)
cout<<"Number is prime:"<<endl;
The code is incredibly false. 33 divided by 2 is 16 with reminder of 1 but it's not a prime number...