VS Studio bizarre output in C++ (prime number check)? - c++

I have a short program consisting of a function that checks, whether a number is prime or not. However the compiler outputs 127 in VS Studio when I invoke the function for the number 3. I want to ask why is that?
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int k) {
for (int i = 2; i < sqrt(i); i++) {
if (k%i == 0) {
return true;
}
else {
return false;
}
}
}
int main()
{
cout << isPrime(3) << endl;
return 0;
}

As commenters have alluded to, your program has undefined behaviour because isPrime doesn't always return from a function you said. From the C++ standard:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
Because you have declared isPrime will return a bool, and you don't always return a bool you have undefined behaviour.
Instead, you probably want to iterate all odd numbers up to k, and check if k is divisible by the number, and if so return false (since it won't be a prime). Otherwise, return true at the end.
It might look like this:
bool isPrime(unsigned long k)
{
for (auto i = 3; i * i <= k; i += 2)
if (k % i == 0)
return false;
return true;
}
I'll leave it to you to work out what to do with 2.

Related

Finding Prime Number: error: control reaches end of non-void function

I was coding to find the prime number and extract the result as a boolean (true/false or 1/0) using the below code.
#include <iostream>
using namespace std;
bool isPrimeNumber(int n) {
int m, i;
m = n / 2;
for (i = 2; i < m; i++) {
if (n % i == 0) {
return true;
} else {
return false;
}
}
}
int main() {
cout << isPrimeNumber(33);
return 0;
}
(Here the result should be 0 since 67 is a prime number)
(I'm skipping negative numbers and 0,1, but I will add it later)
Then on line 9, it said "error: control reaches end of non-void function."
I tried to find the solution on the Internet, and of course, StackOverflow. But my code was still right and buildable.
I think it has something to do with treating warnings as errors (I changed it under recommendation as a beginner). But I don't wanna change it back since I'm still learning.
Do you have a way to solve this problem without changing my setup back to normal?
When n is odd you get the error :
error: control reaches end of non-void function.
You're checking divisibility of n by only one value i=2. You have to check for each value of i from 2 to m.
Return false after iteration of for loop is completed.
Change your isPrimeNumber() function as below:-
bool isPrimeNumber(int n){
int m,i;
m = n/2;
for (i=2;i<m;i++){
if (n % i == 0){
return true;
}
}
return false;
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Value assignment into array c++

I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}
You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.
Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }
It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}
Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number
Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.

C++ What does return function do after if statements in loop?-Prime Test

#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.

bool function for prime numbers

I have the following code for checking whether the first 20 positive numbers are prime using a bool function.
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int);
/*
function to evaluate whether a positive integer is prime (true)
or not prime (false)
*/
int main()
{
for(int x=1; x<=20; x++)
{
cout << x << " a prime ? (1 yes, 0 no) "
<< prime(x) << endl;
}
return 0;
}
bool prime(int x)
{
for(int i=2; i<= sqrt(x); i++)
{
if ((x%i) != 0)
return true;
else
return false;
}
}
It works for all numbers 1 to 20 apart from 2 and 3 where the output is 0 instead of 1. I think I know why. For x = 2 and 3 there is no i in the for loop such that i<=sqrt(2) or i<=sqrt(3).
How could I modify the code so it would work for these values too?
Also there is an error message "Control may reach end of non-void function". Why is this?
Thanks.
Modify your prime function to the following
bool prime(int x)
{
if (x < 2) return false;
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0) return false;
}
return true;
}
The Control may reach end of non-void function error message tells you that your prime function does not return in all cases (When you pass 1 to your function, it does not go in the for loop, and so exit without explicitly returning anything, which could lead to undefined-behavior). In general, you want to have a return instruction outside of any conditionnal structure.
You return in the wrong place in your prime function.
bool prime(int x) {
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0)
return false;
}
return true;
}
In your existing function you only test the very first i. The compiler warning refers to how if the loop finishes without returning (although this is easy for us to see it never will), then control will reach the end of prime without returning a value.
Extract return true result from cycle!
bool prime( int _x )
{
double x = sqrt( _x );
for( int i = 2; i <= x; ++i )
if ( !( _x % i ) )
return false;
return true;
}
you can also use this without need to sqrt function , there it is
bool prime (int num){
int i,temp;
for (i=2; i<=num/2) && temp; i++)
if (num%i==0)
temp = 0;
return temp;}