Random Number Array/ minimum - c++

#include <stdlib.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int minimum(int zahlen[])
{
int minimum;
int o = 0;
bool prüf = false;
while (true)
{
for (int p = 0; p < 20; p++)
{
if (o == zahlen[p])
{
minimum = zahlen[p];
prüf = true;
}
}
if (prüf == true)
{
break;
}
o++;
}
return minimum;
}
void main()
{
srand(clock());
int array[20];
for (int i = 0; i < 20; i++)
{
array[i] = rand();
}
//Minimum
cout << "Die kleinste Zufallszahl die erstellt wurde ist die: " << minimum(array) << endl;
system("PAUSE");
}
Hi,
I have to create a 20 numbers long random array and check for the smallest number.
I know my code is probably not the best method to use for this problem but I am just always getting 371, 374, 202 or 208 as result. Never something else.
Is there a problem I don't see?

It most likely has to do with your use of clock(). According to this, clock() does not give you the current time. It gives you the time since your program started. So everytime you run this program, it takes roughly the same time for it to call clock(), meaning that the random seed is always about the same. To get the actual current world time, use std::chrono::system_clock::now() instead.
Also, an easier way of finding the minimum is this.
int minimum(int _randomNumbers[], int _arraySize)
{
int minimum = _randomNumbers[0]; // By default, let's assume the element 0 has the smallest number.
// Note that in this loop, i starts from 1, since there's no need to compare with element 0.
for (int i = 1; i < _arraySize; ++i)
{
if (_randomNumbers[i] < minimum)
{
minimum = _randomNumbers[i];
}
}
return minimum;
}

Related

Selection Sort Implementation with C++ incorrect

really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Selection Sort :
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
return m;
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void selectionSort(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); ++i)
{
int min = findMin(arr, i);
swap(arr[i], arr[min]); // Assume a correct swap function
}
}
}
void print(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "";
cout << endl;
}
}
}
int main()
{
vector<int> sort;
sort.push_back(2);
sort.push_back(1);
sort.push_back(7);
sort.push_back(4);
sort.push_back(5);
sort.push_back(3);
print(sort);
cout << "this was unsorted array";
cout << endl;
cout << findMin(sort, 0);
cout << "this was minimum";
cout << endl;
selectionSort(sort);
print(sort);
}
I am getting the following results:
comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
}
^
1 warning generated.
2
1
7
4
5
3
this was unsorted array
1
this was minimum
1
2
4
5
3
0
My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"?
Thanks in advance! Sorry for the noob question.
I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well.
You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element.
And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value.
It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop:
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
}
return m;
}

sieve upto 2 billion gives segmentation fault

I am using this program to check a number if prime or not.
Use algorithm - Sieve :
#include<bits/stdc++.h>
//#define _max 2000000001
#define _max 20000001
using namespace std;
bool sieve[_max];
void init()
{
memset(sieve,true,sizeof(sieve));
sieve[0]=sieve[1]=false;
for(int i=2;i<_max;i+=2)
{
sieve[i]=false;
}
}
void go_sieve(int n)
{
n++;
for(int i=3;i<n;i+=2)
{
if(sieve[i]==false)
continue;
for(int j=2*i;j<n;j+=i)
sieve[j]=false;
}
}
void print(int n)
{
n++;
printf("-------------\n");
for(int i=0;i<n;i++)
{
if(sieve[i])
cout << i << " ";
}
printf("\n-------------\n");
}
int main()
{
init();
int n;
scanf("%d",&n);
while(n--)
{
int x;
scanf("%d",&x);
go_sieve(x);
//print(x);
if(sieve[x])
printf("Prime\n");
else
printf("Not prime\n");
}
return 0;
}
Now it works upto 2e7 and pretty smoothly, but I want to check upto 2e9, if I change my _max to 2000000001 it gives me segmentation error and exits with an error code.
How can I resolve this problem ?
I have tried a new approach with set :
#include<bits/stdc++.h>
//#define _max 200001
//#define _max 20000001
#define _max 2000000001
using namespace std;
set<int>prime;
set<int>nprime;
void init()
{
prime.insert(2);
}
void go_sieve()
{
for(int i=3;i<_max;i+=2)
{
if(prime.find(i)==prime.end() && nprime.find(i)==nprime.end())
{
prime.insert(i);
//cout << i << endl;
for(int j=2*i;j<_max;j+=i)
nprime.insert(j);
}
if(nprime.find(i)!=nprime.end())
nprime.erase(nprime.find(i));
}
}
void print()
{
set<int> ::iterator itt;
printf("-------------\n");
for(itt=prime.begin();itt!=prime.end();itt++)
{
cout << *itt << " ";
}
printf("\n-------------\n");
}
int main()
{
init();
go_sieve();
//print();
int n;
scanf("%d",&n);
while(n--)
{
int x;
scanf("%d",&x);
if(prime.find(x)!=prime.end())
printf("Prime\n");
else
printf("Not prime\n");
}
return 0;
}
Target is to execute it within 512MB~1GB memory.
If you want to enumerate large ranges of prime numbers, you should use a segmented Sieve of Eratosthenes; it will be faster (due to caching effects) and use less memory.
If you only want to determine if one number is prime, or a few numbers, sieving is a horrible way to do it. Sieving should only be used when you are interested in an entire range of numbers. For n up to a billion, trial division is simple and probably fast enough. For larger numbers, a Miller-Rabin test or Baillie-Wagstaff test is probably better.
I can't reproduce this on my system. My guess is that this has to do with a system dependant limitation.
You declare sieve as a global array (static storage duration) and it's huge (i.e. 2000000001 * sizeof(bool) - could be 2-8G depending on sizeof bool). Maybe your system can't handle that.
Instead of a global array, try using dynamic allocation:
// bool sieve[_max]; comment out this
bool* sieve = NULL;
...
...
int main()
{
sieve = (bool*)malloc(_max * sizeof *sieve);
if (sieve == NULL)
{
// out of memory
exit(1);
}
...
That said:
Your code is C++ but your style is more C like.
In C++ you would probably use a std::vector instead. That would make everything much easier.
BTW: Also avoid globals. Instead define the vector (or dynamic array) in main and pass it by-reference to the functions.
You probably hit some memory limit on your system which causes the segmentation fault.
However, you don't need such a big array. Using Sieve of Eratosthenes, you need to calculate numbers up to x. Instead of an array you can use std::vector and increase its size as you calculate more numbers. This should allow you to calculate some numbers, but with large numbers you will hit the memory limit again.
You could also use some algorithm which requires you to store fewer numbers. To determine whether x is prime, you only need to compare against prime numbers that are smaller than the square root of x. You don't have to store numbers that are not primes. With x = 1e10, you would only need to store 5e8 numbers.
Here is some example with vector (probably not optimal):
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<int> primes = {2};
void calculate(int x) {
const int largest_prime = primes.back();
if (largest_prime >= x) {
// Already calculated
return;
}
for (size_t i = largest_prime + 1; i <= x; i++) {
bool not_prime = false;
for (size_t j = 0; j < primes.size(); j++) {
if (i % primes[j] == 0) {
not_prime = true;
break;
}
}
if (!not_prime) {
primes.push_back(i);
}
}
}
bool check(int x) {
calculate(x);
return std::find(primes.begin(), primes.end(), x) != primes.end();
}
int main() {
std::cout << check(15) << std::endl;
std::cout << check(256699) << std::endl;
}

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.

BinSearch fails after Bubble Sort

My program seems to be behaving oddly all of a sudden and I cannot figure out why no matter how I look.
Let's begin with the header
//inventoryData.h
//This is the second edition of inventory data, now featuring an actual description
//This header will load an array, sort it, and then be used in InventorySearch to produce parts and prices.
//by Robert Moore on [DATE]
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class InventoryData{
//Variables
private:
int partNum[1000];
double price[1000];
int invCount;
public:
InventoryData();//Build Up
void loadArrays(); //Feed the data from the database into our arrays
void arraySort(); //Bubblesort for the array
int seqSearch(int); //Our one by one search method
int binSearch(int); //The other search
int returnpart(int); //Return Part Number
double returnPrice(int); //Return price
//Incorportate a search counter to both these searches?
//IE: bin search found [x] (completed after [y] records)
};
InventoryData::InventoryData()
{
//Load the array
invCount = 0;
for (int count = 0; count < 1000; count++)
{
partNum[count] = 0;
price[count] = 0;
}
}
void InventoryData::arraySort()
{
int counter = 0; //Used to keep track of subscripts
int temp = 0; //Used to sort subscript contents
double tempPrice = 0;
int maxSub = invCount;
int lastKnown = 0; //Used to indicate what the last swapped value was
char swap = 'Y'; //used to indicate if a swap was made or not
while (swap == 'Y')
{
swap = 'N';
counter = 0;
while (counter < maxSub){
if (partNum[counter] < partNum[counter+1])
{
//Swap the part number
temp = partNum[counter];
partNum[counter] = partNum[counter+1];
partNum[counter+1] = temp;
//Swap the price
tempPrice = price[counter];
price[counter] = price[counter+1];
price[counter+1] = tempPrice;
//Report the swap occured
swap = 'Y';
lastKnown = counter;
}
counter++;
}//End of While Loop
maxSub = lastKnown;
}//End this While Loop Too
cout<<"File sort complete."<<endl;
}
void InventoryData::loadArrays()
{
ifstream partIn;
partIn.open("masterInventory.dat");
cout<<"Loading..."<<endl;
if (partIn.is_open())
{
//Prime Read
partIn >> partNum[invCount]
>> price[invCount];
//cout<<partNum[invCount]<<" and "<<price[invCount] <<" have been loaded."<<endl;
while(!partIn.eof())
{
invCount++;
partIn >> partNum[invCount]
>> price[invCount];
// cout<<partNum[invCount]<<" and "<<price[invCount] <<" have been loaded."<<endl;
} //END While
partIn.close();
cout<<"All files loaded successfully."<<endl;
} //END IF*/
else
{
invCount = -1;
cout<<"File failed to open."<<endl;
}
//arraySort();
}
int InventoryData::seqSearch(int searchKey)
{
int index = 0;
int found = -1;
int counter = 0;
while(index < invCount)
{
counter++;
if (searchKey == partNum[index]
)
{
found = index;
index = invCount;
}
else
{
index++;
}
}
cout<<"(Sequential completed after reading "<< counter<<" files.)"<<endl;
return found;
}
int InventoryData::binSearch(int searchKey)
{
int first = 0;
int last = invCount;
int found = 0;
int mid = 0;
int counter = 0;
while (first <= last && found == 0)
{
counter++;
mid = (first + last)/2;
if (searchKey == partNum[mid] ){
found = 1;
return mid;
}
else
{
if (partNum[mid] < searchKey)
{
first = mid+1;
}
else
{
last = mid - 1;
}
}
}
if (found == 0)
{
mid = -1;
}
cout<<"(Binary completed after reading "<< counter <<" files.)"<<endl;
return mid;
}
int InventoryData::returnpart(int value)
{
return partNum[value];
}
double InventoryData::returnPrice(int value)
{
setprecision(2);
return price[value];
}
With this set up, the program loads numbers from a database (any random combination of digits and another set of "prices"), then we call the function to load, sort, and search the array, as found in the CPP file
//InventorySearch
/*This file is used to search our databases
and return a value for whatever our search may
be looking for.*/
//by Robert Moore
#include "inventoryData.h"
#include <iomanip>
int main()
{
//Declare Variable
int tempSeq = 0;
int tempBin = 0;
int search = 0;
char confirmation = 'Y';
int searchCounter = 0;
int partsFound = 0;
int partsLost = 0;
//Build Object and Load Array
InventoryData invent;
invent.loadArrays();
invent.arraySort();
//Introduction
cout<<"Welcome to Part Search."<<endl;
//Begin Loop Here
while(confirmation != 'N')
{
cout<<"Please enter a part number: ";
searchCounter++;
cin>>search;
cout<<endl;
tempSeq = invent.seqSearch(search);
if (tempSeq != -1)
{
std::cout << std::fixed;
cout<<"Sequential found part number "<<invent.returnpart(tempSeq)<< ", and it's price is "<<setprecision(2)<<invent.returnPrice(tempSeq)<<endl;
partsFound++;
}
else
{
cout<<"Sequential search failed to find part number "<<search<<endl;
partsLost++;
}
tempBin = invent.binSearch(search);
if (tempBin != -1)
{
std::cout << std::fixed;
cout<<"Binary found part number "<<invent.returnpart(tempBin)<<", and it's price is "<<setprecision(2)<<invent.returnPrice(tempBin)<<endl;
partsFound++;
}
else
{
cout<<"Binary search failed to find part number "<<search<<endl;
partsLost++;
}
cout<<"Would you like to search again? (Plese enter Y/N): ";
cin>>confirmation;
confirmation = toupper(confirmation);
}
cout<<"Today's Summary: "<<endl;
cout<<setw(5)<<"Total searches: "<<setw(25)<<searchCounter<<endl;
cout<<setw(5)<<"Total successful searches:"<<setw(15)<<(partsFound/2)<<endl;
cout<<setw(5)<<"Total unsuccessful searches:"<<setw(12)<<(partsLost/2)<<endl;
cout<<"Thank you for using Part Search. Have a nice day."<<endl;
return 0;
}
However, the output runs into the following problem: where the sequential search will scour the entire database and find our value, the binSearch will only search up to 8 values and fail. At first I thought this was due to the way the sort was loaded, but once I coded it out, it continued to fail. Worse yet, aside from adding the sort, the program function just fine prior to this.
I'm running out of ideas as to where the program is wrong, as this code worked just fine up until arraySort() was added.
In your arraySort() method, you should take note of the fact that for instance if maxSub=10, then for the part where you write
while (counter < maxSub){
if (partNum[counter] < partNum[counter+1])
{
.....
}
}
you might end up performing
if(partNum[9]<partNum[10]){
....
}
Since C++ does not perform bound checking on arrays, your code, although buggy, might end up compiling successfully, and may (or may not) produce the correct result. Thus you need to change the loop condition to
while((counter+1)<maxSub){
.....
}
Besides, your arraySort() is sorting in the Descending order, and your binSearch() has been implemented for an array sorted in ascending order. You can change either of the methods as per your requirement.
Hope this helps.
Your sorting algorithm seems faulty to me. If you are trying bubble sort, sorting implementation should be like this.
for(int counter1 = 0;counter1<invCount; ++counter1)
{
for(int counter2 = counter1+1; counter2<invCount; ++counter2)
{
if(partNum[counter1] < partNum[counter2])
{
//do swaping here.
}
}
}

Strange output produced by program

I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that.
Can someone please tell me why.
I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2.
#include <iostream>
bool prime (int i)
{
bool result = true;
int isitprime = i;
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
return result;
}
int main (void)
{
using namespace std;
int PrimeNumbers = 1;
int x = 0;
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
int prime = i;
PrimeNumbers +=1;
}
}
cout<<prime<<endl;
system ("pause");
return 0;
}
cout<<prime<<endl;
prints the address of the function bool prime (int i), not the variable you declared. Just rename the function or the variable (note that you'll also have to change its scope, or move the cout inside the loop - that's if you want to print them all):
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
cout << i << endl;
PrimeNumbers++;
}
}
Also:
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
could be optimized, since (1) you don't need to check all numbers till isitprime, but at most to sqrt(isitprimt) and (2) you only need to check until result is false, at which point you can break out of the loop.
The output isn't strange at all.
cout<<prime<<endl;
You're printing the function pointer of prime here.
You were probably intending to print the variable you create here:
int prime = i;
But this is in the loop scope. In fact, if you compile with warnings enabled, your compiler should tell you that this variable is never used. Also, it's bad practice to give variables in C or C++ the same name as functions (or any other variable in a higher level scope).
Your loop in the main program does not stop correctly because the test variable, PrimeNumbers may not change.
Try:
for (int i = 3; i < 10000; i++)
{
//...
}
Also, because you declared the variable prime inside an if statement, it disappears after the if statement is executed:
if (prime(i))
{
int prime = i; // <-- Declare the variable before the for loop.
//...
The code for finding prime number from nth to 2(1 is neither prime nor composite) is written below, i havent used math.h header file , did something different and surpizingly it works pretty cool....
Code is:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter the number to see primes less than it till 2";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\t"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
if you want to find the prime number from 1 to n,hope this will help u.
#include <iostream>
#include <vector>
static bool _isprime (int number)
{
if(number==1)
{
return false;
}
bool flag=true;
if(number==2||number%2!=0)
{
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=false;
}
}
}
else flag=false;
return flag;
}
int main (void)
{
using namespace std;
vector<int> primenumber;
cout<<"prime number between 1 and ?"<<endl;
int x=0;
cin>>x;
for(int i=0;i<=x;i++)
{
if(_isprime(i)==true)
{
//cout<<x<<" is a prime number"<<endl;
primenumber.push_back(i);
}
//else cout<<x<<" is not a prime number"<<endl;
}
for(int i=0;i<primenumber.size();i++)
{
cout<<primenumber[i]<<endl;
}
cout<<"the number of prime number is "<<primenumber.size()<<endl;
system("pause");
return 0;
}