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;
}
Related
#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;
}
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.
I'm fairly new to programming. I've created a solution to problem 4 on Project Euler. However, my code seems to have a problem and doesn't give me the desired result. The problem at hand is to find the largest palindrome created by multiplying two 3 digit numbers. The code works fine when I start both the loops at 100 (which is to find the largest palindrome obtained by multiplying two 2 digit numbers). My output, in this case, is 90909, whereas it should be 906609. Can anyone please review my code and help me?
#include "iostream"
using namespace std;
int checkPalindrome(int);
int main()
{
int prod;
for(int i=1000;i>0;i--)
for(int j=1000;j>0;j--)
{
prod=i*j;
if(checkPalindrome(prod))
{ cout<<prod;
cout<<endl;
exit(0);
}
}
}
int checkPalindrome(int x)
{
int temp=0,copy;
copy=x;
while(x!=0){
temp=temp*10+(x%10);
x/=10;
}
if(copy==temp)
return 1;
else
return 0;
}
Your are not actually searching for the largest palindrome created by multiplying two 3 digit numbers with your solution but you are instead searching for the first palindrome that the loops find. You can make it right like this:
int main()
{
int prod;
int res = 0;
for (int i = 1000; i > 0; i--)
for (int j = 1000; j > 0; j--)
{
prod = i*j;
if (checkPalindrome(prod) && res < prod)
{
res = prod;
}
}
cout << res;
cout << endl;
exit(0);
}
I am having a run-time error in this program, it has no syntax error but crashes when it is run. i am using dev-c++ 4.9.9.2. I tried to find the error but i couldn't find it. If anyone can help then please find the errors and correct me.
#include<iostream.h>
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
main()
{
DisplayVUID();
char a[20] = "mc123456789";
DisplayReverse(a, 20 );
StoreDiagonal();
system("pause");
}
void DisplayVUID()
{
int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
for(i=0;i<20;i++)
{
cout<<name[i];
}
cout<<endl;
}
void DisplayReverse(char a[], int arraysize)
{
int i;
cout<<"MY VU id in Reverse is ";
for(i=arraysize-1;i>=0;i--)
{
cout<<a[i];
}
cout<<endl;
}
void StoreDiagonal()
{
int a[9][9] ;
int i;
int row, col;
for (i = 0; i<9;i++)
{
for(i=0;i<9;i++)
{
a[row][col] = 0;
}
}
a[1][1] = 1;
a[2][2] = 3;
a[3][3] = 0;
a[4][4] = 2;
a[5][5] = 0;
a[6][6] = 2;
a[7][7] = 3;
a[8][8] = 9;
a[9][9] = 8;
for(i = 0 ; i < 9 ; i ++)
{
for( i = 0 ; i < 9 ; i ++)
{
cout<<a[row][col];
}
}
}
Things don't work this way on Stackoverflow, from next time onward try hard to do things on your own, do your research and then come here.There seemed to be many errors in your program but I tried to remove some bugs and finally, It works on my system. I have also recommended some nice things via comments that you can look in the program:
EDIT: I noticed that some undefined string because of unassigned spaces in the array was printed out in the reverse function but i have corrected it now.
#include<iostream>
#include<stdlib.h>
using namespace std;// use namespace otherwise cout won't work
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
int main()// In C++ always declare a main function like this,its good habit
{
int i=0;
DisplayVUID();
char a[20] = "mc123456789";
while(a[i]!='\0')
i++;// Did this to ensure that cout will print only up to the null character,earlier it was printing some undefined characters along with the data in the array.
DisplayReverse(a, i );
StoreDiagonal();
system("pause");
return 0;//return 0
}
void DisplayVUID()
{
//int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
//for(i=0;i<20;i++)// no need for this loop at least here
//{
cout<<name;
//}
cout<<endl;
}
void DisplayReverse(char a[], int i)
{
cout<<"MY VU id in Reverse is ";
// for(i=arraysize-1;i>=0;i--)
//{
while(i--)
cout<<a[i];//instead of the for loop traversing for the whole arraysize i have made it go up to only the null terminator this way it doesn't print undefined characters.
//}
cout<<endl;
}
void StoreDiagonal()// i don't understand by the way what this function is here for , its not an error though.
{
int a[9][9] ;
int i,j,c=1;
//int row, col;// you didn't initialize row and column and placed it inside the loop
for (i = 0; i<9;i++)
{
for(j=0;j<9;j++)
{
a[i][j] = 0;
if(i==j)
{
a[i][j]=c;//instead of manually assigning do it like this.
c++;
}
}
}
for(i = 0 ; i < 9 ; i ++)
{
for( j = 0 ; j < 9 ; j ++)
{
cout<<a[i][j];// the elements of the array don't display like a table , this is not an error but to make your output readable do it by your self
}
}
}
a[9][9]=8;
remove this line, you will be fine. Array indexing starts from 0 not 1.
Also I would like to point that in your function DisplayVUID() change i<20 to a[i]!='\0' because the values after '\0' will be garbage values.
I'm trying to implement the Sieve by myself and with no help other than the algorithm provided...
#include <iostream>
using namespace std;
void findPrimeNumbers(int number) {
int n=0;
bool* boolArray = new bool[number]();
for(int i=0; i<number; i++) {
boolArray[i] = true;
}
for(int i = 2; i<(int)sqrt(number); i++) {
cout << "calculating...\n";
if(boolArray[i]) {
for(int j=(i^2+(n*i)); j<number; n++)
boolArray[j] = false;
}
if(boolArray[i])
cout << i << "\n";
}
return;
}
int main()
{
findPrimeNumbers(55);
system("pause");
return 0;
}
Except the program is hanging on line 37; specifically, "boolArray[j] = false". It's never exiting that loop, and I don't know why.
Edited: Ok, this fixes the hang but still isn't right, but don't answer, I want to figure it out :)
#include <iostream>
#include <cmath>
using namespace std;
void findPrimeNumbers(int number) {
int n=0;
bool* boolArray = new bool[number]();
for(int i=0; i<number; i++) {
boolArray[i] = true;
}
for(int i = 2; i<sqrt(number); i++) {
if(boolArray[i]) {
for (int j = pow(i,2) + n*i; j <= number; j = pow(i, 2) + (++n*i))
boolArray[j] = false;
}
if(boolArray[i] && number % i == 0)
cout << i << "\n";
}
return;
}
int main()
{
findPrimeNumbers(13195);
system("pause");
return 0;
}
Beyond the error pointed out by #Rapptz (^ is bitwise xor), you are incrementing n instead of j, so the termination condition is never reached.
Two problems:
The ^ operator is not the exponent operator like it is in some other languages. Just multiply i by itself instead (i*i).
your for loop:
for(int j=(i^2+(n*i)); j<number; n++)
boolArray[j] = false;
does not reevaluate the initial condition each loop. You need to reevaluate the condition at the beginning of the for loop:
for(int n=0; j<number; n++)
{
j=(i*i+(n*i));
boolArray[j] = false;
}
Your issue is the line i^2+(n*i) like the comments point out, operator^ is the XOR operator, not exponentiation. In order to exponentiate something you have to include the <cmath> header and call std::pow(a,b) where it is equivalent to the mathematical expression a^b.
Although you didn't ask for code review, it should be noted that using dynamic allocation for a bool array is probably not a good idea. You should use std::vector<bool> and a proper reserve call. It should also be noted that the pow call would be completely unnecessary, as you are only multiplying it by itself (i.e. 2^2 is the same as 2*2).
A better naive prime sieve would be something similar to this:
#include <vector>
#include <iostream>
template<typename T>
std::vector<T> generatePrimes(unsigned int limit) {
std::vector<T> primes;
std::vector<bool> sieve((limit+1)/2);
if(limit > 1) {
primes.push_back(2);
for(unsigned int i = 1, prime = 3; i < sieve.size(); ++i, prime += 2) {
if(!sieve[i]) {
primes.push_back(prime);
for(unsigned int j = (prime*prime)/2; j < sieve.size(); j += prime)
sieve[j] = true;
}
}
}
return primes;
}
int main() {
std::vector<unsigned> primes = generatePrimes<unsigned>(1000000);
for(auto& i : primes)
std::cout << i << '\n';
}
You can see it here.
You have a number of problems:
int j=(i^2+(n*i))
^ is not power in C++, it's the bitwise XOR operator. To fix this, you'll need to #include <cmath> and utilize pow, or simply use i * i.
Secondly, as others have mentioned, you are incrementing n. The easiest fix for this is to use a while loop instead:
int j = std::pow(i, 2) + (n*i);
while(j < number) {
//Set bool at index to false
j += i;
}
Thirdly, you have a memory leak - you new without a delete. Further, there's no reason to use new here, instead you should have:
bool b[number];
This will deallocate b automatically when the function exits.
Finally, why return at the bottom of a void function? Technically you can do it, but there is no reason to.