Random numbers in the output - c++

I've been coding in c++ for over a day now and I am currently stuck on this particular problem. I want to enter a integer and produce every prime numbers that are smaller than the given integer but the output always has random numbers that aren't prime. Here's the code:
#include <iostream>
#include <math.h>
using namespace std;
int check(int x){
bool prime = true;
if (x <= 1){
prime = false;
return 0;
}
for (int i = 2; i < x; i++){
if (x % i == 0){
prime = false;
return 0;
}
}
if (prime = true){
return x;
}
}
int main(){
int r;
cout << "Enter range: ";
cin >> r;
int primes[r];
int n = 0;
for (int i = 0; i < r; i++){
if (check(i) != 0){
primes[n] = i;
n++;
}
else{
}
}
for (int i : primes){
cout << i << endl;
}
}
Help me fix this problem. Thanks.

The problem in your code is that you check numbers in the range [0,r] and assume to find r prime numbers in that range. Thats of course not correct. For example when in the range [0,r] there are p prime numbers then your output will print the p prime numbers and then r-p uninitialized values (thats undefined behavior, the output of your code could be anything).
Change the last loop to
for (int i=0; i<n; ++i) {
cout << primes[i] << endl;
}
To see only entries of primes that you actually assigned a value in the loop before.
Also please consider that int primes[r]; is not standard C++. See here: Why aren't variable-length arrays part of the C++ standard?. Use std::vector for dynamically sized arrays. Actually in your code you do not need an array at all. You can simply print the prime numbers in the same loop where you check them:
if (check(i) != 0) { std::cout << i << "\n"; }
Moreover, your check is a little too complicated. You are using a flag that you don't need. The last if is wrong, because prime = true is assignment not comparison. However, that doesnt really matter because at that point prime is always true (if not you already returned), and prime=true does evaluate to true. The function can look like this:
int check(int x){
if (x <= 1){
return 0;
}
for (int i = 2; i < x; i++){
if (x % i == 0){
return 0;
}
}
return x;
}
This will also prevent the compiler from issuuing a warning for not returning from all branches. Note that you only need to check factors <= sqrt(x) because when there is a factor bigger than that there must also be a factor smaller than that.

Related

How to solve RUN_ERROR even though it compiles normally?

I am currently writing a script about finding the nearest duplicate from a user entered size array.
The array must be between 1 and 10^5 and its value has to be between 1 and 10^5 also.
It compiles normally on my computer but whenever I submit it, it returns a run_error.
Here's what I wrote.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void input (int *);
int main(){
int n;
input (&n);
int a[n];
for(int i=0;i<n;i++){
if (scanf("%d",&a[i])!=1)
return 0;
if ((a[i]>100000)||(a[i]<1))
return 0;
}
for (int i=0;i<n;i++){
if (a[abs(a[i])]>=0){
a[abs(a[i])]=-a[abs(a[i])];
} else {
printf("%d",abs(a[i]));
return 0;
}
}
return 0;
}
void input(int *x){
if (scanf("%d",x)!=1)
exit(0);
if ((*x>100000)||(*x<1))
exit(0);
}
This program is logically incorrect. There is no connection between the size of the array defined in n and the limit of the allowed elements.
Since you have allowed a[i]>100000 to go up to 10^5 with no regards to the size of the array defined by a[n], the following access will attempt to access outside the bounds of the array, a[abs(a[i])] for any a[i] > n.
Also, you can pass by reference for syntactical simplicity
input(n);
void input(int &x){
if (scanf("%d",&x)!=1)
exit(0);
if (x>100000 ||x<1)
exit(0);
}
First of all, if you are writing in C, please tag this question as C question, and not as C++ one. scanf & printf are C functions, as much as your includes stdio.h & stdlib.h & math.h. In c++ you have the include iostream, and in this case it's all you really need.
The second problem here is the way you handle the input validation when it wrong. exit is very dangerous way, and very not recommended. If you want to throw exception use throw method (Read about the difference between the two: https://stackoverflow.com/a/56406586/8038186). But, in this case I don't understand why do you need to throw exception at all. you can simply finish the program in more gentle way. Consider the following flow:
#include <iostream>
using namespace std;
// Num is moved by reference and not by pointer
bool input(int &num) { // return true if the input is good, otherwise return false.
cout << "Please enter number: " << endl; // Tell the user that he should enter a number.
cin << num;
bool is_valid = num >= 1 && num <= 1e5; // 1e5 = 100000
if (!is_valid) cout << "Invalid input." << endl;
return is_valid;
}
int main() {
int n;
if (!input(n)) {
return 0;
}
int a[n];
int i;
for (i = 0; i < n && input(a[i]); i++);
if (i < n) {
return 0;
}
for (i = 0; i < n; i++) {
// The following if is useless, the validation make sure already that all of the numbers are legal.
//if (a[a[i]] >= 0) { // You don't need abs(a[i]), a[i] > 1
if (a[i] < n)
a[a[i]] = -a[a[i]];
else cout << "Consider what do you want to do" << endl;
/*} else {
printf("%d", a[i]);
return 0;
}*/
}
return 0;
}
Read about the difference between reference and pointer: What are the differences between a pointer variable and a reference variable in C++?

Can someone help me with rectifying the output of this "Prime Numbers below 100" code?

This Question has been answered
So basically, I just wrote down a code to display all the prime numbers below 100. This is the code:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<n/2; i++)
{
if (n%i==0)
{
goto restart;
}
else
{
cout<<n<<"\t";
}
}
restart:
n++;
}
return 0;
}
But instead of the output being 2 3 5 7 11 ..... it comes out as:
All prime numbers below 100 are:
7 9 11 11 11 13 13 13 13 15 15 and so on ...
I just want the output to display all prime numbers starting from 2 to 97 without repetitions. thank you.
/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/--/-/-/-/-
I got out of the problem with a slight modification.
#include<iostream>
using namespace std;
int main()
{
int n=2, i;
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if(n%i==0)
{
goto label;
}
}
cout<<n<<", ";
label:
n++;
}
return 0;
}
Thank you to everyone for your valuable time. (And the reason why I use such beginner type codes is I've just started out on C++ like a week ago. I have so much more codes (like bool, isPrime, etc.) to learn.)
Keeping Cranking 'em codes, fellow coders :D
There is an obvious error in your algorithm. You might be able to find it using a debugger, but I think that a better way would be for you to learn about extracting a function. What you want your main function to do, is exactly: if n is prime: output n. So you should write it that way:
int main()
{
for (int i = 0; i < 100; ++i)
if (is_prime(i))
std::cout << i << std::endl;
}
Of course for that to work you'll need to define the function is_prime:
bool is_prime (int n) {
for (int i = 2; i * i <= n; ++i)
if (n % i == 0)
return false;
return true;
}
Note also that there is no need to check if n is divisible by numbers greater then it's square root. If there are no divisors up to the square root, the next possible divisor is n itself.
As others mentioned, that's not the optimal algorithm to solve this problem, but for small values it's definetely good enough.
Your answer is OK but has two critical errors. Firstly, you output n for each modulo you check. You should only output n if all the modulo checks fail. Also, your boundary condition isn't quite right - it should be <=. Working code with minimal changes would be:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if (n%i==0)
{
goto restart;
}
}
cout<<n<<"\t";
restart:
n++;
}
return 0;
}
If you wanted to make slightly cleaner code then dont use goto, use a double for loop and a break. Also your boundary condition for i should be i*i<=n as thats a tighter bound. So something like:
#include <iostream>
int main()
{
cout<<"All Prime numbers below 100 are : \n";
for(int n=2; n<100; ++n)
{
bool isPrime = true;
for(int i=2; i*i<=n; i++)
{
if (n%i==0)
{
isPrime = false;
break;
}
}
if(isPrime)
std::cout<<n<<"\t";
}
}
You are trying to check if each number is prime. Therefor you have to check if it is dividable by a smaller number.
A more efficient way to find all prime numbers up to a maximal number is the Sieve of Erathosthenes:
#include <iostream>
#include <vector>
int main() {
const unsigned int maxNum(100);
std::vector<bool> prime(maxNum, true);
for (unsigned int i(2); i*i < maxNum; ++i) {
if (!prime[i]) continue;
for (unsigned int j(2*i); j < maxNum; j += i) {
prime[j] = false;
}
}
for (unsigned int i(2); i < maxNum; ++i) {
if (prime[i]) std::cout << i << std::endl;
}
return 0;
}
A list of all numbers is created. Each multiple of of each number is removed from this list.

Print the maximum non perfect square

I'm trying to make a c++ program that finds the maximum non perfect square in an array and print it, perfect square i.e. x = y^2 => 4 = 2^2.
Here is what I've tried and doesn't work for me, don't know why:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
sqrt(arr[i]);
if ((arr[i] * 10) % 10 == 0)
arr[i] = arr[1];
else
arr[i] = arr[0];
}
for (int i = 0; i < n; i++)
{
if (arr[0] < arr[i])
arr[0] = arr[i];
}
cout << arr[0] << endl;
return 0;
}
My logic is to take the square root of each array element and check if it's non-perfect or perfect. If we multiply the element by 10, then take modulus of 10, then we know whether it is an integer or decimal. For example: 2*10 = 20, 20%10 = 0 (perfect square), otherwise it is not perfect. Then, I stored each non-perfect square in arr[0], in the next loop I'm supposed to find the largest non perfect square and print it. What am I doing wrong?
PS:
Consider arr[variable] is valid, because it works in CodeBlocks. Thank you!
You lost the result of sqrt. sqrt(arr[i]) does not change arr[i]).
You improperly check if a square root is an integral. You should cast a result of sqrt to int, multiply it by itself and compare with arr[i].
I left you free to update your code properly yourself.
You can use this logic to find if a number is perfect-square or not, this is one way to find largest non perfect square of an array of positive numbers, initialize answer=-1 before you enter the loop, n is the size of the array
double answer = -1,temp;
for(int i=0;i<n;i++){
if((temp = array[i]) != (sqrt(array[i])*sqrt(array[i]))){
if(temp > answer){
answer = temp;
}
}
}
#include <iostream>
#include <cmath>
using namespace std;
int main () {
int n;
cin>>n;
int k[n];
double arr[n];
for (int i = 0 ; i < n ; i++){
cin>>k[i];
arr[i]=sqrt(k[i]);
int j = arr[i];
if (arr[i]==j){
arr[i]=0;
}
}
double m=0;
int index = 0;
for (int i = 0; i < n; i++){
if (arr[i]>m){
m=arr[i];
index = i;
}
}
cout << k[index];
}
Here is a code. We introduce a double, such that it can store the decimals. Then we introduce an integer. If the square root of the number is a decimal, it is not a perfect square. However, when I introduce this integer j, it will convert arr[i] to an integer. If the number is a perfect square, then arr[i] is an integer, and j==arr[i]. We do not want that, so we put that equal 0. We find the largest array, and mark the index. Then we print out the original number in the original array with that index. i have added this as float does not store every single decimal point.
To clarify: lets say arr[i]=4.55556. Then j=4. arr[i]!=j. If arr[i]=5, j=5, arr[i]=j, and then arr[i] is set to 0.

recursive algorithm to sum of every element in an array with a value lesser than x

I'm a beginner to c++ and I'm trying to write an recursive algorithm that returns the sum of every element in an array with a value less than x.
Here is my code:
#include <iostream>
using namespace std;
int sumOfElement(int xList[],int x, int lengthOfArray){
int sum = 0;
if (lengthOfArray == 0)
return sum;
else
for (int i=0; i <= lengthOfArray; i++) {
if(xList[i] < x)
return sum + xList[i];
else
sumOfElement(xList,x,lengthOfArray-1);
}
}
int main() {
cout << "Size of Array: ";
int size;
cin >> size;
int *xList = new int[size];
//Inputing array.
cout << "Enter elements of array followed by spaces: ";
for (int i = 0; i<size; i++)
cin >> xList[i];
cout << "Enter the integer value of x: " <<endl;
int limit;
cin >> limit;
cout << "Sum of every element in an array with a value less than x: " << sumOfElement(xList,limit,size) << endl;
return 0;
}
I'm using Visual Studio, while I was running the code, I got this warning: "warning C4715: 'sumOfElement' : not all control paths return a value. " And the program always stop executing when it asks me to enter the integer value for x.
What's wrong with my code?
Your approach here isn't really recursive. The idea with recursion is to consider a base case, and then consider how to reduce the problem at each step until you get to the base case.
For this problem:
The base case is when the length of the array is zero. In this case we return a sum of zero. (Intuitively: if the array is empty then we're adding nothing, giving a sum of zero.)
In order to reduce our array we look at the last element of the array (ie. at lengthOfArray - 1). We process this element: if it's less than x we add it, if it's not then we ignore it. We then get the result of processing the rest of the array by the same means (by calling the same function, but with a different array length), and add our result if applicable.
So, some example code:
int sumOfElement(int xList[], int x, int lengthOfArray){
if (lengthOfArray == 0) {
// base case
return 0;
} else {
int value = xList[lengthOfArray-1];
if (value < x) {
// process the rest of the array and add our result
return value + sumOfElement(xList, x, lengthOfArray - 1);
} else {
// process the rest of the array
return sumOfElement(xList, x, lengthOfArray - 1);
}
}
}
for (int i=0; i <= lengthOfArray; i++)
{
if(xList[i] < x)
return sum + xList[i];
else sumOfElement(xList,x,lengthOfArray-1);
}
You shouldn't have a for-loop, and recursive functions should "return" the deeper call, so
int retVal = 0;
if(xList[lengthOfArray-1] < x)
retval = xList[lengthOfArray-1]
return retVal + sumOfElement(xList,x,lengthOfArray-1);

How to solve 8 queens 1D array with brute force?

I was given an assignment to modify an 8 Queens program to use a 1D array and to use brute force (already did backtracking). I've come up with the following code:
#include <cmath>
#include <iostream>
using namespace std;
bool ok(int board[8]){
for(int j = 0; j <= 7; j++){ //check for repeating digits
cout << "ok loop 1"<<endl;
for (int k = 0; k <= 7; k++)
{
cout << "ok loop 2"<<endl;
if (board[k] = board[j]){ return false; }
}
}
for(int c = 7; c >= 0; c--){ //check if position is safe
cout << "ok loop 3"<<endl;
//int r = 0;
for(int i = 1; i <= c; i++){
cout << "ok loop 4"<<endl;
if(board[c-i] == c)
return false;
else if ((board[c]-i)>0 && board[c-i]-i == 1)
return false;
else if ((board[c]+i)<=7 && board[c-i]+i == 1)
return false;
} // for loop
} // for loop
return true;
} // ok
void print(int board[8], int c){
cout << "Solution " << c << ": " << endl;
for(int i = 0; i < 8; i++){
{
cout << board[i] <<" ";
}
}
cout << endl;
}
int main ()
{
int b[8]={0}; //initialize the array
int count = 0;
for(b[0]=0; b[0]<8; b[0]++)
for(b[1]=0; b[1]<8; b[1]++)
for(b[2]=0; b[2]<8; b[2]++)
for(b[3]=0 ; b[3]<8; b[3]++)
for(b[4]=0; b[4]<8; b[4]++)
for(b[5]=0; b[5]<8; b[5]++)
for(b[6]=0; b[6]<8; b[6]++)
for(b[7]=0; b[7]<8; b[7]++)
if(ok(b))
{
count++;
print(b, count);
}
system("PAUSE");
return 0;
}
It keeps looping forever and I am not sure why. Would anyone mind helping me?
There's a few things that could be improved:
If you passed a reference to a constant array of eight chars to ok() instead of just a pointer to non-const ints, the compiler could have told you about one of the issues.
How many different positions can a queen have? I'd say 64, though your code suggests eight. I'd start with documenting the actual meaning of variables and constants throughout your code, because you seem to be confused there yourself.
You check if board[x] is board[y], but with x and y being equal, and from that you claim that there are repeating digits.
You make a difference between the different queens. In other words, your program will find all permutations of how the queens could be positioned on the same eight positions. This is not incorrect, but inefficient. If you fix the number of positions, that will make a noticeable difference.