Trying to count all the prime numbers but my output is crazy - primes

#include <iostream>
using namespace std;
int main ()
{
int count = 0;
for (int x=2; x < 100; x++)
for (int y=2; y < x; y++)
{
if (x % y == 0)
break;
else if (x == y + 1)
count++;
cout << x << " ";
cout << count;
system("pause")
return 0;
}
I want to print the prime numbers and also print out the number of prime numbers between 2 and 100. which should be 24. Instead I get a ton of repeats of the prime numbers and then the number 24. I'm sure it's a logical error, just not catching it.

First, there are syntax errors.
Second, always use curly braces with if/else unless you know what you are doing - there's an error related to this.
Third, using system() requires #include <cstdlib>. Your compiler is lax if it allows you to not to (g++ doesn't).
Fourth, pause is not a standalone program but a cmd.exe builtin so system() may fail depending on the compiler/environment used. A neater way is C++ keypress: getch, cin.get? .
Finally, your algorithm is highly suboptimal. E.g. y only needs to go up to x/2+1 and it's reasonable to store the primes already found in an array/list and try only them.

Related

Why do i need to subtract 7 from the while condition in the end for my code to work correctly

I am new to coding and i am trying to print fabonacci sequence and i cannot understand why i am unable to get the output correct without subtracting 7 from my while loop condition . And can anyone tell me how to fix this problem.
#include<iostream>
#include<cmath>
using namespace std;
int main (){
double y;
double z;
int x;
cout <<"Enter the number you want to find the sequence of :";
cin>>x;
int zero = 1;
cout<<"Sequence equal to or less than "<<x<<" is :"<<"0";
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
cout<<","<<y;
} while(y<=x-7);
}
You "need" to subtract 7 because you want the last value printed to be smaller than x, but you check the condition after printing. Putting the -7 makes the last value printed smaller than x sometimes, but not always. Try x = 123 to get output 0,1,1,2,3,5,8,13,21,34,55,89,144 or x = 3 to get 0,1 while it should be 0,1,1,2,3.
To fix your code first check the condition and only then print it:
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
if (y <= x) {
cout<<","<<y;
} else {
break;
}
} while(true);
The issue is there's too much happening in this loop:
int zero = 1;
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
cout<<","<<y;
} while(y<=x-7);
You are combining the iteration of zero, with the computation of y, with the check against x. Spelling out every step is error-prone, and if the loop is more than a few lines it becomes hard to tell what's going on. If your loop is not doing what you want, a good approach is to abstract out the details of the loop by wrapping that in a function.
For example, simply by refactoring the computation of y, like this:
auto fib = [](int zero) {
return ceil((std::pow(1.618,zero) - std::pow(-0.618,zero)) / 2.236);
};
You can use a much more natural loop construct for the problem:
for(int zero = 1; (y = fib(zero)) <= x; ++zero)
std::cout<<","<<y;
Here's a demo.
This is still more complexity than necessary. From c++20, you could declare all the fibonacci numbers:
auto fib_nums = std::views::iota(1) | std::views::transform(fib);
This has the nice advantage that it can be used for different purposes, and keeps generating fibonacci numbers forever.
Now your loop can just do the needed comparison:
for(int y : fib_nums | std::views::take_while([x](int y) { return y <= x; }))
std::cout << "," << y;
Here's a demo.

The compiler doesnt show errors but I get no output. Whats wrong?

I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
bool PerfectCheck(int x) {
int t; // divisor
int sum; // sum of divisors
for (t = 0; t <= x; t++ ) {
if (x%t == 0) {
sum = sum + t;
}
}
if (sum == x)
return true;
else
return false;
}
int main() {
srand(time(NULL));
int x = rand()%(100-2+1)+2;
if (PerfectCheck(x) == true )
cout << x << "is a perfect number.";
else
cout << x << "is not a perfect number.";
return 0;
}
There are three problems in your PerfectCheck function. First, you don't initialize the sum variable, so it can start off with any value whatsoever; you should set it to zero explicitly in the declaration.
Second, your for loop starts with t as zero, and you check x % t. The modulo operator implicitly involves a division, so using a left-hand value of zero has the same issue as trying to divide by zero, which will cause a crash.
Third, when checking for a perfect number, don't use that number itself in the sum; so, stop your loop with t < x instead of t <= x.
Also, as mentioned in the comments, you can simplify the return statement. The code below works, in the tests I have performed:
bool PerfectCheck(int x)
{
int sum = 0; // sum of divisors - MUST BE INITIALIZED (to zero)
for (int t = 1; t < x; t++) { // DO NOT INCLUDE X ITSELF!!
if (x % t == 0) {
sum += t;
}
}
return (sum == x); // This will already give a "true" or "false" bool value.
}
You could actually make the code a tiny bit more 'efficient', by initializing sum to 1 and then starting the loop from t = 2 (all numbers divide by 1, after all).
Feel free to ask for further clarification and/or explanation.
if (x%t == 0) calculates the remainder after dividing x by t and compares the result with 0. That statement is correct, but look at the previous code for (t = 0; t <= x; t++ ) {. The first value of t is 0, so you have a division by zero. More than likely that is crashing your program which is why you see no output. Change for (t = 0; t <= x; t++ ) { to for (t = 1; t <= x; t++ ) {.
Also I believe the definition of a perfect number does not include division by the number itself. So the for loop should actually be for (t = 1; t < x; t++ ) {.
Finally you are using the sum variable to add up the divisors but you do not give it an initial value. Your code should say int sum = 0;.
Three errors in a ten line program (plus various style issues). Imagine how many errors here might be in a 5000 line program. Programming is tricky, you have to be very focused and get your code exactly right, nearly right is not good enough.

basic nestled loop calculate prime numbers between 1 - 239, inclusive

I am working on a program in which I must print out the number of primes, including 1 and 239, from 1 - 239 ( I know one and or two may not be prime numbers, but we will consider them as such for this program) It must be a pretty simple program because we have only gone over some basics. So far my code is as such, which seems like decent logical flow to me, but doesnt produce output.
#include <iostream>
using namespace std;
int main()
{
int x;
int n = 1;
int y = 1;
int i = 0;
while (n<=239)
{x = n % y;
if (x = 0)
i++;
if (y < n)
y++;
n++;
while (i == 2)
cout << n;
}
return 0;
}
The way I want this to work is to take n, as long as n is 239 or less, and preform modulus division with every number from 1 leading up to n. Every time a number y goes evenly into n, a counter will be increased by 1. if the counter is equal to 2, then the number is prime and we print it to the screen. Any help would be so greatly appreciated. Thanks
std::cout << std::to_string(2) << std::endl;
for (unsigned int i = 3; i<240; i += 2) {
unsigned int j = 3;
int sq = sqrt(i);
for (; j <= sq; j += 2) if (!(i%j)) break;
if (j>sq) std::cout << std::to_string(i) << std::endl;
}
first of all, the prime definition: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
so you can skip all the even numbers (and hence ... i+=2).
Moreover no point to try to divide for a number greater than sqrt(i), because then it will have a divisor less than sqrt(i) and the code finds that and move to the next number.
Considering only odd numbers, means that we can skip even numbers as divisors (hence ... j+=2).
In your code there are clearly beginner errors, like (x = 0) instead of x==0. but also the logic doesn't convince. I agree with #NathanOliver, you need to learn to use a debugger to find all the errors. For the rest, good luck with the studies.
lets start with common errors:
first you want to take input from user using cin
cin>>n; // write it before starting your while loop
then,
if (x = 0)
should be:
if (x == 0)
change your second while loop to:
while (i == 2){
cout << n;
i++;
}

If we list all the natural numbers below 10 that [C++]

The code that I did was for solving the following problem. However, the logic of the code is wrong and I as a good newbie cannot figure what is wrong.
After I compile the result of 'sum' is always 0, if I change the initialization of 'sum' for a whatever number, that whatever number is what appear as answer of 'sum'.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
long sum = 0;
for( long i; i < 1000; ++i )
{
if (( i % 3 == 0 ) || ( i % 5 == 0 ))
{
sum = sum + i;
}
}
cout << "The sum is: " << sum << endl;
return 0;
}
You need to initialize i in your loop:
for (long i = 0; i < 1000; ++i )
As it is, i is probably some random number greater than 0 at the top of the loop, and the result is that the loop is never executed.
You need to initialize i to zero otherwise i's value will be whatever happens to be in memory. In this case it's > 1000.
for (long i = 0; i < 1000; ++i)
Also, a nice trick I learned. Use ii as your index variable. It's much easier to find ii than just i in your code.
You forgot to set i=O in your loop so the loop won't iterate.
All answers above are correct - you need to set your i to 0. What you might be interested in is that accessing uninitialized variable is an "undefined behaviour" (UB) and modern compilers are actually pretty good in finding the UBs and using them to optimize the code. For example, GCC 5.2 with -O2 (optimizations enabled) will generate same assembly for your code and for one without the loop at all regardless of what might happen to be in the memory at the address of i.
Try putting this code to (which is your code with additional #if for convenience) this online disassembler
#include <iostream>
using std::cout;
using std::endl;
int main()
{
long sum = 0;
#if 1
for (long i; i < 1000; ++i)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
sum = sum + i;
}
}
#endif
cout << "The sum is: " << sum << endl;
return 0;
}
add the -O2 flag to compiler options on top right and try changing #if 1 to #if 0 and observe that the disassembly is the same meaning that the compiler cut out the loop completely.

main() not executing, but compiling

I have this simple program:
// Include libraries
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Include locals
// Start
#define NUMBER 600851475143
int main(int argc, const char* argv[])
{
long long int ans = 0;
long long int num = NUMBER;
vector<int> factors;
do
{
// Get lowest factor
for (int i = 1; i <= num; ++i)
{
if (!(num % i))
{
factors.push_back(i);
num /= i;
break;
}
}
} while (num > 1);
cout << "Calculated to 1.\n";
int highestFactor = numeric_limits<int>::min();
for (int i = 0; i < factors.size(); ++i)
{
if (factors[i] > highestFactor)
{
highestFactor = factors[i];
}
}
ans = highestFactor;
cout << ans << endl;
return EXIT_SUCCESS;
}
compiling with g++ -O2 -c -o prob3.o prob3.cpp proved successful, but when I ran it I saw nothing and it just kept running and I had to Ctrl-C (force-kill) it in the end. When I try to add
int main(int argc, const char* argv[])
{
cout << "Test\n";
to the program, Test didn't get printed too. It's like my program is not executed at all.
Any help or advice is appreciated!
Solution
I forgot prime numbers started at 2. Change for (int i = 1 to for (int i = 2.
Those nested loops are going to loop forever. The inner for loop will only ever execute once because of the break so it will only ever do num /= 1. That means num never decreases and so num > 1 will never be false. I suppose you just need to wait longer!
The reason you're not seeing "Test" is probably because you haven't flushed the output. Try:
std::cout << "Test" << std::endl;
Your program is simply running. It takes a long time to execute.
For the cout << "Test\n";, it's a matter of the cout stream not being flushed: what you wrote to the stream is still in your program memory and not yet flushed to the system to be printed.
Have you tried to start your for condition from 2? The module function doesn't have sense if start from 1.
if (!(num % i))
Num / 1 give 0, so you're not enter in the if condition
Your loop is an infinite loop. The first factor you find is 1 (since num % 1 is 0) and as such you divide num by 1 which results in num which re-enters the for loop, which does the same again and again.
Also with this fixed (initialize i in the loop with 2), your inner for loop is most likely an infinite loop and/or causing UB. Otherwise (as the others stated) it is "just" running very long. For the case where it is different (assuming most common platforms here). This depends on the value you are trying to factor, if the first factor is smaller than std::numeric_limits<int>::max() then this does not apply. Lets call those primes BIGPRIME (600851475149 would be a good example).
long long int is at least 64bit in size. int is unlikely to be bigger than 32bit on most platforms, so when it is not bigger on your platform it can only go up to std::numeric_limits<int>::max() which is (again assuming the common 32bit platform here) 2147483647 which is in turn promoted in the comparison to long long int but keeps its value, which is always smaller than BIGPRIME. Always increasing i does never get anywhere, and once you are at max() you enter UB land as signed integers don't wrap in C++. Your code might infinite loop there, or do some things like recording -1 as a valid factor, or make you pregnant.
You can easily observe that by adding some
if( 0 == (i%100000000)){ std::cout << i << std::endl; }
into the for loop.