Whats wrong with my Prime number Checker? - c++

I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...

To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'

//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).

First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).

Related

Print all prime number lower than n in C++ ( file crash )

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.

putting different values in return statement of c++

// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1){
return (a * factorial (a-1)); }//function calling itsself
else
return 0;
}
main ()
{
long number = 2;
cout << number << "! = " << factorial (number);
}
i am begginer learning objects and classes. i get some code from my context but its getting some error.
how return statement is working when its value is 0 out put becomes 0 when it is return 1 output is 2. when it is return 3 output is 6 similar for 4 is 8.
Here's a calculator to compute factorial
#include <iostream>
using namespace std;
int Factorial(int long long a) {
int long long Ans = 1;
for (int x = 1; x <= a; x++) {
Ans *= x;
}
return Ans;
}
int main() {
int Input;
cin >> Input;
if (Input > 0) {
cout << Factorial(Input);
}
}
Calling a function from within itself is generally considered bad practice, so avoid it. Use long long if you need larger numbers. Also, try to provide more information about your question.

Program to calculate square root c++

I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
Here is my full code:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance.
Below explanation is given for the integer square root calculation:
In number theory, the integer square root of a positive
integer n is the positive integer m which is the greatest integer less
than or equal to the square root of n
The approach your started is good but needs several correction to make it work:
you are working with int you want to add 1 to squareroot not 0.1
you want to stop your calculation when you squareroot * squareroot is equal or greater than number. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
in the case of number equal to 26, do you want to return 5 or 6? After your while loop the value of squareroot will be 6 so you might want to reverse it to 5 (if squareroot * squareroot is different than number)
Below the exemple:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
This function uses Nested Intervals (untested) and you can define the accuracy:
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
See https://en.wikipedia.org/wiki/Nested_intervals
This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
The problem with your code, is that it only works if the square root of the number is exactly N*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check this wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
if you don't want to import math.h you can write your own abs():
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
Square Root of a number, given that the number is a perfect square.
The complexity is log(n)
/**
* Calculate square root if the given number is a perfect square.
*
* Approach: Sum of n odd numbers is equals to the square root of n*n, given
* that n is a perfect square.
*
* #param number
* #return squareRoot
*/
public static int calculateSquareRoot(int number) {
int sum=1;
int count =1;
int squareRoot=1;
while(sum<number) {
count+=2;
sum+=count;
squareRoot++;
}
return squareRoot;
}
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here https://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Greatest Common Divisor using Euclidian Algorithm?

So I'm having a problem with my code here.
I am coding a Greatest Common Divisor using the Euclidian Algorithm and I can't seem to utilize the loop in order to keep the division to keep repeating until I get the greatest common divisor. So for now, I am able to get the remainder but do not know how to go on from there basically.
Any help will be greatly appreciated!
Here is what I have so far
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int a;//Holds the first number
int b;//Holds the second number
int temp;//Assign to greatest number
int hold;//Assign to smaller number
float euclid;//soon to be function?
int leftover;
float gcd;
int main ()
{
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
if (a>b)//Determines bigger number
{temp=a;
hold=b;
}
if (a<b)//Determines smaller number
{
temp=b;
hold=a;
}
leftover= temp%hold;
cout<<"\nThe remainder of the two numbers divided is "<<leftover<<".\n"<<endl;
}
Actually there is no need to calculate bigger number the euclid's algorithm manages itself.
Here's the working code :
#include <iostream>
using namespace std;
int gcd(int m,int n)
{
if(n == 0)
return m;
return gcd(n, m % n);
}
int main()
{
int a,b,answer;
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
answer = gcd(a,b);
cout << "The GCD of the two numbers is : " << answer << endl;
return 0;
}
Do not forget to handle negative numbers in algorithm.
gcd(m, n) = gcd(n, m%n) when n != 0
= m when n = 0
function:
int gcd(int m, int n) {
if(m == 0 && n == 0)
return -1;
if(m < 0) m = -m;
if(n < 0) n = -n;
int r;
while(n) {
r = m % n;
m = n;
n = r;
}
return m;
}

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