Hey, so I've been learning my c++ and I've been trying to solve a problem.
So far I've learned about
while, for, loops
if,else statements
Functions
I guess, pretty much the basics.
So i was presented with a problem, the problem being
Write a program that lets the user enter any number n and then finds
the first prime number larger than n.
So my soloution was
#include "stdafx.h"
#include <iostream>
#include <math.h>
double square (double a) ; // square root finding function
int modulus(int a, int b , double c, int d) ; // function to find whether number is prime or not
using namespace std ;
int main ()
{
int prime = 0 ;
double n; // Number that prime number must be > than.
double i ; //Number to test primeness on
int l=2; //loop
cout << "Please enter the value that the first prime number must be greater than! " << endl ;
cin >> n ;
i=n ;
i++; // set i greater than n
while(i<n){
modulus (i, l, n, prime) ;
if ( prime=0){ // if modulus returns prime=0
i++ ; } // increase i, to run loop again, with greater number
if (prime=1)// if modulus returns prime=1
cout << "The number " << i << " is the first prime number after " << n << endl;
break; // end loop as prime number is found
}
getchar();
getchar();
}
double square (double a)
{
return sqrt(a);
}
int modulus (int a, int b, double c, int d) {
for (b=2; b<=square(c) ; b++) {
if (a%b==0){ // This would mean the number is not prime
d=0 ;
return d=0 ;
}
if (b>=square(c)) { // if b becomes equal to or greater than the number, the number would be prime
return d=1;
}
}
}
I've looked at this code a million times and I just cant figure out why it doesnt work?
It builds succesfully, (just gives me a warning on conversion from double to int, which is fine)
When i run it however, i get to the first step, entering the number which the prime number must be > than
BUT then the program just asks me to press any key to continue and exits!
It totally skips my loop, although the condition is already met!
Can someone help me out here???