C++: find first prime number larger than a given integer - c++

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.

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

Finding the smallest prime factor using recursion c++

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

Sum of factoriais to be equal a given number

I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

C++ factorial of 0

I am writing a program to find the factorial of a user inputted number. My program works from, except for finding the factorial of 0. The requirement is that the factorial of 0 should output one, but I cannot think of a way to write this capability into the code without creating a special case for when 0 is entered. This is what I have so far
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int startingNumber = 0;
double factorialize = NULL;
while(startingNumber != -1) {
cout << "Enter the numbr to factorial: ";
cin >> startingNumber;
factorialize = startingNumber;
for(int x=startingNumber-1;x>=1;x--) {
factorialize = factorialize*x;
}
cout << factorialize << endl;
factorialize = NULL;
}
return 0;
}
This outputs a factorial accurately for all cases except 0. Is there a way to do this that doesn't require a special case? I am thinking no because when I read about the reasons for why 0! is 1, it says that it is defined that way, in other words, you cannot reason your way into why it is 1. Just like x^0, 0! = 1 has a different logic as to why than why 2^2 is 4 or 2! = 2.
try this:
factorialize = 1;
for(int x=2; x<=startingNumber;x++)
factorialize *= x;
Try this:
for (unsigned int n; std::cin >> n; )
{
unsigned int result = 1;
for (unsigned int i = 1; i <= n; ++i) { result *= i; }
std::cout << n << "! = " << result << "\n";
}
You can change the result type a bit (unsigned long long int or double or long double), but ultimately you won't be able to compute a large number of factorials in hardware.
First of all I do not see how it can be calculated accurately, as you multiply startingNumber twice. So just fix the logic with:
factorialize = 1.0;
for(int x=startingNumber;x>=1;x--) {
factorialize = factorialize*x;
}
And it should calculate factorial properly as well as handling 0 the proper way.
Also you should not use NULL as initial value for double, it is for pointers.
There is a complete factorial of number program of C++ which includes the facility of factorial of positive number,negative and zero.
#include<iostream>
using namespace std;
int main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0
)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read full program logic on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
The function listed below returns the factorial FASTER than any solution posted here to this date:
const unsigned int factorial(const unsigned int n)
{
unsigned int const f[13] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600 };
return f[n];
}
I looks silly but it works for all factorials that fit into a 32-bit unsigned integer.

Prime number C++ program

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