list of prime numbers between 1 and 100 - c++

I want to find the list of prime numbers, I try this code but it doesn't show me anything:
#include <iostream>
using namespace std;
int main()
{
int n, i;
std::cout << "Liste des nombres premiers : " << std::endl;
for (n = 1; n < 100; n++) {
for (i = 2; i < n; i++) {
if (n % i == 0)
std::cout << n << " ";
}
}
return 0;
}

I don't like your code at all. Try to do this: create a function that tells you if a number is prime, and then go with a for loop through all numbers from 1 to 100, and check with the function if they are prime.
Here is an easy to remember function (for natural numbers):
bool isPrime(int n)
{
if (n <= 1)
return 0;
if (n == 2)
return 1;
if (n%2 == 0)
return 0;
for (int i=3; i*i <= n; i+=2)
if (n%i == 0)
return 0;
return 1;
}
This function returns 1 if the number is prime, and returns 0 if it isn't.
The idea is this:
If n is 0 or 1, it is not prime.
If n is 2, it is prime.
If n is a multiple of 2, but it isn't 2, it is not prime.
Then, you have to check if n has any divisors until you get to square root of n (i * i <= n)

To correct program errors:
Initialize the value of n as 2.
And print when i is equal to n not when n % i is 0. It should be rather n % i == 0 then break.
Change i < n to i <= n.
Try the first approach (used sqrt()):
#include <iostream>
#include <cmath>
int main(void)
{
for (int i = 2; i < 100; i++) {
if (i == 2 || i == 3) { // if number is 2 or 3, then prints it
std::cout << i << ' ';
}
for (int j = 2; j * j <= i; j++)
{
if (i % j == 0) break;
else if (j + 1 > sqrt(i)) std::cout << i << ' ';
}
}
return 0;
}
Alternative approach:
#include <iostream>
int main(void)
{
for (int n = 2; n < 100; n++)
for (int i = 2; i <= n; i++)
if (i == n) std::cout << i << ' ';
else if (n % i == 0) break;
return 0;
}

Related

Why is this code not printing the prime factors of num?

I wrote this code for obtaining the prime factors of a number taken as an input from the user.
#include<bits/stdc++.h>
using namespace std;
void prime_Factors(int);
bool isPrime(int);
int main()
{
int num;
cout << "Enter the number to find it's prime factors: ";
cin >> num;
prime_Factors(num);
}
void prime_Factors(int n1)
{
for(int i = 2; i<n1; i++)
{
if(isPrime(i))
{
int x = i;
while(n1%x==0)
{
cout << i << " ";
x *= i;
}
}
}
}
bool isPrime(int n0)
{
if(n0==1)
return false;
for(int i = 0; i*i <= n0; i++)
{
if(n0%i==0)
return false;
}
return true;
}
The prime_Factors() function call in main() function is not printing the prime factors. Pls help!!
The ranges of the loops are wrong.
Firstly, the loop for(int i = 2; i<n1; i++) will fail to find prime factors of prime numbers (the numbers theirself). It should be for(int i = 2; i<=n1; i++).
Secondly, the loop for(int i = 0; i*i <= n0; i++) will result in division-by-zero. It should be for(int i = 2; i*i <= n0; i++).
Thinking about using the Sieve of Eratosthenes made me try it out:
#include <iostream>
#include <cstdint>
#include <vector>
void prime_factors(uint32_t n) {
while(n % 2 == 0) {
std::cout << "2 ";
n /= 2;
}
std::vector<bool> sieve(n / 2, true);
for (uint32_t i = 3; i * i <= n; i += 2) {
if (sieve.at(i / 2 - 1)) {
uint32_t j = i * i;
for (; j < n; j += 2 * i) {
sieve.at(j / 2 - 1) = false;
}
if (j == n) {
do {
std::cout << i << " ";
n /= i;
} while (!sieve.at(n / 2 - 1));
}
}
}
if (n > 1) std::cout << n;
std::cout << "\n";
}
int main() {
prime_factors(123456789);
}
https://godbolt.org/z/8doWbYrs6

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}

Converting argv arguments to int

I have tried atoi, strol, and stoi but none of them are working for me. I've even tried to subtract '0' from the char which I heard should work but that threw an error too. atoi gives me a Segmentation Fault, strol won't compile, and stoi gives me an std logic error. here is my entire program as of right now:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
bool isPrime(int);
int main (int argc, char *argv[])
{
const int size = 199;
int counter = 1;
int primeAry[size];
for (int i = 0; i < size; i++) // creates an array of prime numbers
{
if (isPrime(i))
{
primeAry[counter] = i;
counter++;
}
}
for (int j = 1; j <= argc; j++) // finds prime numbers by index of args and displays them
{
if (j == 1)
cout << "Last name is " << argv[j] << endl;
else
{
int temp = atoi(argv[j]);
cout << temp << " th prime number is " << primeAry[temp] << endl;
}
}
system("pause");
return 0;
}
bool isPrime(int num)
{
if(num <= 1)
return false;
else if (num <= 3)
return true;
else if (((num % 2) == 0) || (num % 3) == 0)
return false;
int i = 5;
while((i*i) <= num)
{
if ((num % i == 0) || ((num % (i + 2)) == 0))
return false;
i = i + 6;
}
return true;
}
And here is the result I get:
Last name is smith
1 th prime number is 2
2 th prime number is 3
3 th prime number is 5
Segmentation Fault
I've been working on this forever and I've searched every forum that I could find but I can't figure out what I'm missing.
Segmentation Fault**
You get segmentation fault when you pass NULL to atoi. This is happening because your loop bounds are incorrect. This:
for (int j = 1; j <= argc; j++)
should instead be
for (int j = 1; j < argc; j++)
In C, you should treat all loops with <= terminating condition with extreme suspicion. More often than not that's where the bug is hiding.

C++: Pascal's triangle - weird results

This is my first question so don't be mad at me, if I did something wrong.
I have to make a C++ program which returns an element from a selected row, for example:
Triangle 4 0 1 2 3
should return elements: 0, 1, 2 and 3 from row number 4, but it returns strange things, like:
Element 0: 1
Element 1: 10179988
Element 2: 50792126
Element 3: 91425820
I have no idea why
Here's my code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int *tab;
public:
Pascal(int n) throw(string) {
if (n < 0)
throw (string)"";
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
};
int element(int m) {
return tab[m];
}
};
int main(int argc, char* argv[]) {
int n = 0, m = 0, elem = 0;
try {
n = strtol(argv[1], NULL, 0);
Pascal *row;
for(int i = 2; i < argc; i++) {
try {
m = strtol(argv[i], NULL, 0);
row = new Pascal(n+1);
if (m <= n && m >= 0) {
elem = row->element(m);
cout << "Element " << m << ": "<< elem << endl;
} else
cout << m << " - bad element index" << endl;
} catch (string ex) {
cout << argv[i] << " - bad element index!" << endl;
continue;
}
delete[] row;
}
} catch (string e) {
cout << argv[1] << " - bad row index!" << endl;
return 0;
}
}
I'll be grateful for any answer
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
first iteration: i=1, k=1, tab[1]+=tab[0];
second iteration: i=1, k=2, tab[2]+=tab[1];
So you are not properly initializing your array, you are simply adding whatever values are in memory...
I think replacing if (k - 1 >= 0) with if (k - 1 > 0) should solve your problem
Try
tab = new int[n+1];
for(int i = 0; i <= n; i++) {
tab[i] = 1;
for(int k = i; --k > 0; )
tab[k] += tab[k-1];
}

C++ Recursion Character Printing

Edit: Corrected Code (Thanks for the answers and help!)
#include <iostream>
using namespace std;
int arr1(const int n,int i, int j){
if(j != 0) {
/* if(i == 2*n ){
cout<<"\n";
--j;}*/
if((i <= (n-j) || (i >= (j+n)) && i <2*n)){
cout<<" ";
}
if(i < n && i > (n-j)){
cout<<"\\";
}
if( i > n && i < (n+j)){
cout<<"/";
}
if(i == n){
cout<<"v";
}
if(i == 2*n ){
cout<<"\n";
i = 0;
--j;}
return arr1(n,++i,j);
}
return 0;
}
int main(){
int c;
cin>>c;
arr1(c,1,c);
}
I'm trying to write a program that takes an integer n and recursively prints an arrowhead type design
n=1 -> v
n=2 -> \v/
v
n=3 -> \\v//
\v/
v
etc:
This is my code so far, yet I keep getting a segmentation error. I assume this because of an infinite loop somewhere in the code.
#include <iostream>
using namespace std;
int arr1(const int n, int i, int j)
{
if (j != 0)
{
if (i == 2 * n)
{
cout << "\n";
--j;
}
if (i <= n - j || i >= j + n)
{
cout << "_";
}
if (i < j)
{
cout << "\\";
}
if (i > j)
{
cout << "/";
}
if (i == n)
{
cout << "v";
}
return arr1(n, ++i, j);
}
return 0;
}
int main()
{
int c;
cin >> c;
arr1(c, 1, c);
return 0;
}
The decision of whether to recurse comes down to the value of j -- but you receive j from main, and never modify it afterwards unless i==2*n, passing the exact same value when it calls itself recursively. So yes, that leads to infinite recursion (assuming you originally pass a non-zero value for j, anyway).
You logic in the arr1 function is wrong, for example, if c=3 in the beginning,
the i, j, n values in arr1 will be in each iteration
i = 1 j = 3 n = 3
i = 2 j = 3 n = 3
i = 3 j = 3 n = 3
i = 4 j = 3 n = 3
i = 5 j = 3 n = 3
i = 6 j = 2 n = 3
i = 7 j = 2 n = 3
i = 8 j = 2 n = 3
i = 9 j = 2 n = 3
i = 10 j = 2 n = 3
i = 11 j = 2 n = 3
...
then it goes for ever until stack overflow.