I am new to c++ and I have been tasked to write a code which finds the smallest prime factor of a number using recursion. If N is less than 2 the code should return 1. If N is a prime number itself the code should return N. Otherwise the code should return the smallest prime factor of N. I have attempted the question but I have used a for loop to check for the lowest prime factor and I am unsure if this method in the context of my answer is iterative or recursive. To call the function for main the user should enter lowestPrimeFactor(x);, where x is the number they want to find the lowest prime factor for. I am stuck with trying to change the iterative section to recursive, where the code checks for the lowest prime factor. I would appreciate any feedback.
#include <stdio.h>
#include <iostream>
#include <math.h>
long lowestPrimeFactor(long N, long i=2) {
if(N<2){ //if N is less than 2, return 1
std::cout << 1; //print to screen to check
return 1;
}
bool isPrime =true; //Check if number is prime
for(i=2;i<=N/2; ++i){
if(N%i==0){
isPrime=false;
break;
}
}
if (isPrime){
std::cout<<N;
return N;
}
for (int i = 3; i* i <= N; i+=2){ //This is where I am unsure how to translate to recursive as it is based of an iterative solution
if(N%i == 0)
std::cout<<i;
return i;
}
//Driver code to check functionality
int main(){
lowestPrimeFactor(19);
}
EDIT
I think I have modified the code correctly to be recursive for the prime factor check
//Recursive
if(i*i<=N){
N%i==0; lowestPrimeFactor(i);
}
else return i;
Just need to try and adjust the bool part to be recursive too
Try this:
#include <iostream>
using namespace std;
long lowestPrimeFactor(long N, long i = 2) {
if (N % i == 0) // Test for factor
return i;
else if (i < N * N)
return lowestPrimeFactor(N, i + 1); // Test next factor
else
return N;
}
void test(long N){
// Format results
cout << N << " gives " << lowestPrimeFactor(N) << endl;
}
int main() {
for (long N = 2; N < 30; ++N) // Generate some test cases
test(N);
}
This has the inefficiency that it tests for non-prime factors too (which I think the original solution also does) so really rather than recursing with i + 1 (the next integer after i) we should be calculating and passing in the next prime after i.
The required code, if you want to use recursion for checking out the lowest prime factor instead of the last for loop would be as follows:
#include <iostream>
long lowestPrimeFactor(long N,long pr = 3)
{
bool isPrime =true;
if(N<2)
{ //if N is less than 2, return 1
std::cout << N << std::endl;//print to screen to check
return 1;
}
else
{
for(long i=2;i<=N/2; ++i)
{
if(N%i==0)
{
isPrime=false;
break;
}
}
}
if(isPrime)
{
std::cout << N << std::endl;
return N;
}
else
{
if(N%2==0){
std::cout << 2 << std::endl;
return 2;
}
else
{
if(N%pr == 0)
{
std::cout << pr << std::endl;
return pr;
}
else
{
return lowestPrimeFactor(N,pr+2);
}
}
}
}
//Driver code to check functionality
int main()
{
lowestPrimeFactor(19);
lowestPrimeFactor(20);
lowestPrimeFactor(7);
lowestPrimeFactor(1);
lowestPrimeFactor(15);
}
This isn't fully recursive but it checks for only prime numbers till 7 after which it checks for 9 and so on i.e odd numbers which even the original code had.
Note: Prime factors it checks properly: 2,3,5,7 and prime numbers
Related
I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.
Question: How to find, for a given integer n, the first prime number that is larger than n?
My own work so far
I've managed to write a program that checks whether or not a given integer is a prime or not:
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime (int n)
{
int i;
double square_root_n = sqrt(n) ;
for (i = 2; i <= square_root_n ; i++)
{
if (n % i == 0){
return false;
break;
}
}
return true;
}
int main(int argc, char** argv)
{
int i;
while (true)
{
cout << "Input the number and press ENTER: \n";
cout << "To exit input 0 and press ENTER: \n";
cin >> i;
if (i == 0)
{
break;
}
if (is_prime(i))
cout << i << " is prime" << endl;
else
cout << i << " isn't prime'" << endl;
}
return 0;
}
I'm struggling, however, on how to proceed on from this point.
You have a function is_prime(n), and a number n, and you want to return the smallest number q such that is_prime(q)==true and n <= q:
int q = n;
while (!is_prime(q)) {
q++;
}
// here you can be sure that
// 1. q is prime
// 2. q >= n -- unless there was an overflow
If you want to be a bit more efficient, you can check explicitly for the even case, and the increment by 2 each time.
It's a concrete example of a general theme: if you have a test function and a method for generating elements, you can generate the elements that pass the test:
x = initial_value
while (something) {
if (test(x)) {
// found!
// If you only want the first such x, you can break
break;
}
x = generate(x)
}
(note that this is not a valid C++ code, it's pseudocode)
int i;
**int k_koren_od_n = (int)(sqrt(n) + 0.5)**
for (i = 2; i <= k_koren_od_n ; i++){
To get around casting issues, you might want to add this fix.
Here is the problem I am trying to solve:
Define a class named PrimeNumber that stores a prime number. The default constructor should set the prime number to 1. Add another constructor that allows the caller to set the prime number. Also, add a function to get the prime number. Finally, overload the prefix and postfix ++ and -- operators so they return a PrimeNumber object that is the next largest prime number (for ++) and the next smallest prime number (for --). For example, if the object's prime number is set to 13, then invoking ++ should return a PrimeNumber object whose prime number is set to 17. Create an appropriate test program for the class.
This is not for a class, I am just trying to teach myself C++ because I need it as I will start my PhD in financial mathematics at FSU this fall. Here is my code thus far:
#include <iostream>
#include "PrimeNumber.h"
using namespace std;
int main() {
int x;
cout << "\nenter prime number: ";
cin >> x;
PrimeNumber p(x);
PrimeNumber q(x);
p++;
q--;
cout << "\nprime before is " << q.GetPrime() << endl;
cout << "\nnext prime is " << p.GetPrime() << endl;
return 0;
}
class PrimeNumber {
int prime;
public:
PrimeNumber():prime(0){};
PrimeNumber(int num);
void SetPrime(int num);
int GetPrime(){return prime;};
PrimeNumber& operator++(int);
PrimeNumber& operator--(int);
static bool isPrime(int num);
};
void PrimeNumber::SetPrime(int num) {
if(isPrime(num)){
prime = num;
}else{
cout << num << " is not a prime Defaulting to 0.\n";
prime = 0;
}
}
PrimeNumber::PrimeNumber(int num){
if(isPrime(num))
prime = num;
else {
cout << num << " is not prime. Defaulting to 0.\n";
prime = 0;
}
}
PrimeNumber& PrimeNumber::operator++(int){
//increment prime by 1 and test primality
//loop until a prime is found
do
{
this->prime += 1;
}
while (! PrimeNumber::isPrime(this->prime));
}
PrimeNumber& PrimeNumber::operator--(int){
do
{
this->prime -= 1;
}
while (!PrimeNumber::isPrime(this->prime));
}
bool PrimeNumber::isPrime(int num) {
if(num < 2)
return false;
if(num == 2)
return true;
if(num % 2 == 0)
return false;
const int max_divisor = sqrt(num);
for(int div = 3; div < max_divisor; div += 2) // iterate odd numbers only
if(num % div == 0)
return false;
return true;
}
So, my question here is that for the bool isPrime function, I first say OK the prime numbers 2 and 3 are primes and then I eliminate any numbers that are multiples of 2 or 3. What I want to do is perhaps create a while loop that would eliminate the other multiples of the number leaving the prime numbers only. Although, I am not exactly sure how to achieve this, if anyone has any suggestions, I would greatly appreciate it.
Now that is taken care of, I can't seem to get the ++ and -- operators working correctly. Sometimes it works and sometimes it doesn't.
What I want to do is perhaps create a while loop that would eliminate the other multiples of the number leaving the prime numbers only. Although, I am not exactly sure how to achieve this, if anyone has any suggestions, I would greatly appreciate it.
The algorithm you want to apply is called the Sieve of Erathostenes.
Instead of doing that (it would require that you store more and more prime numbers as you increment an instance), consider the algorithm proposed by Juraj Blaho (that tends to be the simplest).
Edit: consider this algorithm instead:
bool PrimeNumber::isPrime(int num) {
if(num < 2)
return false;
if(num == 2)
return true;
if(num % 2 == 0)
return false;
const int root = sqrt(num);
for(int div = 3; div <= root; div += 2) // iterate odd numbers only
if(num % div == 0)
return false;
return true;
}
This is much faster (for large numbers) than the solution proposed by Juraj Blaho.
End Edit.
If you are instead looking for partial solutions (almost prime numbers, numbers that are "probably prime") consider the Rabin-Miller probabilistic primality test (or other tests linked to, from that page).
To check if a number is prime, you just need to check the remainder after division of each number smaller than square root of the tested number. Additionally some extra checks need to be performed for numbers smaller or equal to 1.
bool isPrime(int x)
{
if (x <= 1)
return false;
for (int i = 2; i * i <= x; ++i)
if (x % i == 0)
return false;
return true;
}
If an optimized version without any floating point calculations and square roots is needed:
bool isPrime(int x)
{
if (x <= 1)
return false;
if (x <= 3)
return true;
if (x % 2 == 0)
return false;
for (int i = 2; ; i += 2)
{
const auto result = std::div(x, i);
if (result.rem == 0)
return false;
if (result.quot < i)
return true;
}
return true;
}
#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
int prime(int n)
{
int i;
if (n == 1) return 0; // zero- not prime
if (n == 2) return 1; // one- prime
for (i = 2; i <= ceil(sqrt(n)); i++) {
if (n % i == 0) return 0; // remainder is zero
}
return 1;
}
int main()
{
unsigned long n;
while (cin >> n) {
cout << prime(n) << endl;
}
}
I know that 0 means not prime and 1 means prime. Can someone please explain how are all the return functions used to accomplish this?
Why not use cout << "0" for not prime and cout << "1" for prime?
Yes, you could cout directly from the function. That would be valid.
But when you make a mathematical function, it's more conventional to return its value, so that the code that called it can then do whatever it likes. It can cout it, or save it to a variable, or perform other calculations.
If the function directly couted the result, then you're stuck: it can only do that one thing with the result. That's limiting, and for no benefit.
I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}