Not able to execute below prime no program - primes

I am trying write a simple prime number code from 1 to 100, but I am unable to understand why its not giving me result.
package com.java.program;
public class PrimeNo {
public static void main(String[] args) {
System.out.println("Prime no btw 1 to 100");
for(int i=1;i<=100;i++)
{
int count=0;
for(int j=2;j<=i;j++){
if(i%j==0)
{
count++;
break;
}
}
if(count==0)
{
System.out.println("\t" +i);
}
}
}
}

just do j< i and it will print. because the number n will always be divisible by n so its not printing primes between 2 and 100
for(int j=2;j<i;j++)

In first for loop start i from 2 instead of 1. In your second for loop you are doing (j <= i). A number is always divisible by itself and hence it makes count++ and it is ignored when j = i. Try this (j < i) or for efficiency (j <= i/2+1).

Related

Determining prime number

Im doing exercise from the Bjarne Stroustrup book called "Programming principles and practice using c++". I have to find first n prime numbers that user wants[user enters 5, and program finds first five prime numbers]. I found the solution on this site:
http://people.ds.cam.ac.uk/nmm1/C++/Exercises/Chapter_04/ex_15.cpp
bool prime (vector<int> table, int number) {
for (int i = 0; i < table.size(); ++i)
if (number%table[i] == 0) return false;
return true;
}
but i cant understand the test for primality. Why modulo? I have my own test for primality and its much easier to understand for me, albeit its less elegant and more verbose.
bool isPrime(int num) {
for (int i = 2; i < num; i++) {
for (int j = 0; j < num; j++) {
if (i*j == num) {
return false;
}
}
}
if (num == 1) {
return false;
}
return true;
}
So if anyone can explain me that guy code i would be greatful.
Here's the other code, included in its entirety:
#include "std_lib_facilities.h"
bool prime (vector<int> table, int number) {
for (int i = 0; i < table.size(); ++i)
if (number%table[i] == 0) return false;
return true;
}
int main () {
int count, next;
cout << "Input the number of primes\n";
cin >> count;
vector<int> table;
next = 2;
while (table.size() < count) {
if (prime(table,next)) table.push_back(next);
++next;
}
for (int n = 0; n < table.size(); ++n)
cout << table[n] << " ";
cout << endl;
// keep_window_open();
return 0;
}
This code populates the vector table with all the prime numbers it has found so far. Starting from 2, it checks if the number is divisible by any of the numbers in this table it has constructed. If it isn't divisible, it means that this number is a prime, and it gets entered into the table.
The modulo operator is used to check for divisibility here. a%b returns the remainder that occurs when the division a/b is performed. If this value is 0, there is no remainder, and we can conclude that a is divisible by b.
The modulo operator returns the remainder of a division operation. So if the remainder is equal to 0 for any of the numbers in the table, then we can say that the number is evenly divisible, and therefore not prime. On the other hand, if the modulo returns anything other than 0 for all of the numbers in the table, the number is not evenly divisible, and therefore it is prime.
https://www.cprogramming.com/tutorial/modulus.html
Welcome to StackOverflow :)

Hello how to prevent this func from print 1 with the prime numbers array

Hello i write this func to print the prime number from 2d array
put when i enter for example 1 2 3 4 5 6 7 8 it print 1 2 3 5 7
how can i edit it to not
Change your outer if statement to
if (count == 0 && o[i][j] != 1) {
c[I] = o[i][j];
I++;
p++;
}
It would be easier to write a function that checks if a number is prime and call that function for each matrix element. Also there are more efficient ways to determine if a number is prime.
I added some comments to explain what is going on, but in advance, you are going to ignore '1' from the result list, so I added "if(o[i][j]!=1)", in the other hand, to find the prime list, if the first number is dividable, you will not need to count other numbers, so you can add "break;" in the for(...)
void FindPrime(int o[5][5]){
int c[100];int I=0 ,count=0,p =0;
int i,j,h;
for(i =0;i<5;i++)
{
for(j =0;j<5;j++)
{
count =0;
for(int k =2;k<o[i][j];k++)
{
if(o[i][j]% k == 0)
{
if(o[i][j]!=1)// Do not add 1 to the array
{
count++;
// To make the function faster you can add "break;" here. If find the first dividable number, don't continue for
}
}
}
if(count == 0)
{
c[I] = o[i][j];
I++;
p++;
}
}
}
for(int I =0;I<p;I++)
{
h=c[I];
cout<<" "<< h <<" ";
}
cout<<"\n\n";
}

Error trying to find all the prime numbers from 2 to n using Sieve of Eratosthenes in C++

I need to find all the prime numbers from 2 to n using the Sieve of Eratosthenes. I looked on Wikipedia(Sieve of Eratosthenes) to find out what the Sieve of Eratosthenes was, and it gave me this pseudocode:
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
So I used this and translated it to C++. It looks fine to me, but I have a couple errors. Firstly, if I input 2 or 3 into n, it says:
terminate called after throwing an instance of 'Range_error'
what(): Range_error: 2
Also, whenever I enter a 100 or anything else (4, 234, 149, 22, anything), it accepts the input for n, and doesn't do anything. Here is my C++ translation:
#include "std_lib_facilities.h"
int main()
{
/* this program will take in an input 'n' as the maximum value. Then it will calculate
all the prime numbers between 2 and n. It follows the Sieve of Eratosthenes with
the algorithms from Wikipedia's pseudocode translated by me into C++*/
int n;
cin >> n;
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
The issue is coming from the fact that the indexes are not in line with the value they are representing, i.e., they are moved down by 2. By doing this operation, they no longer have the same mathematical properties.
Basically, the value 3 is at position 1 and the value 4 is at position 2. When you are testing for division, you are using the positions as they were values. So instead of testing if 4%3==0, you are testing that 2%1=0.
In order to make your program works, you have to remove the -2 shifting of the indexes:
int main()
{
int n;
cin >> n;
vector<string>A;
for(int i = 0; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
I agree with other comments, you could use a vector of bools. And directly initialize them with the right size and value:
std::vector<bool> A(n, false);
Here you push back n-1 elements
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
but here you access your vector from A[2] to A[n].
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
A has elements at positions A[0] to A[n-2]. You might correct this defect by initializing your vector differently. For example as
vector<string> A(n+1, "true");
This creates a vector A with n+1 strings with default values "true" which can be accessed through A[0] to A[n]. With this your code should run, even if it has more deficits. But I think you learn most if you just try to successfully implement the sieve and then look for (good) alternatives in the internet.
This is painful. Why are you using a string array to store boolean values, and not, let's say, an array of boolean values? Why are you leaving out the first two array elements, forcing you to do some adjustment of all indices? Which you then forget half the time, totally breaking your code? At least you should change this line:
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
to:
i -= 2; // because I left the first two elements out, I that here.
// But only here, doing it everywhere is too annoying.
As a result of that design decision, when you execute this line:
for(int j = pow(i, 2); j <= n; j += i)
i is actually zero which means j will stay zero forever.

Need a function to continue decreasing a value once it runs out of valid values

So Im writing a function that is supposed to count up all the first N even numbers in an array where the user picks N. Which is fine, however if there are fewer than N even numbers in the array, then the function should just add them all which is the part I am having difficulty with.
function call:
cout << "The sum of the first " << userSum << " even numbers is: " <<
SumEvens(list, SIZE, userSum) << endl;
function definition:
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i < size; i++){
if (arr[i] % 2 == 0 && arr[i] != 0){//if the number is even and not 0 then that number is added to the sum
evensAdd--;
sum += arr[i];
}
if(evensAdd == 0)//once evensAdd = 0(N as previously mentioned) then the function will return the sum
return sum;
}
}
So for example if I have an array: {1,2,3,4,5}
and ask for it to calculate the sum of the first 2 even numbers it would output 6
however if i ask for it to calculate say the first 3 or 4 or 5 even numbers it will output that the sum is 6
why would it subtract one?
If you finish the for loop before evensAdd reaches 0, you never reach the return sum statement and therefore not set the return value of the function. The value returned is then just a random number read from the stack. This is just a technical stuff, the correct approach should look like this:
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 == 0 && arr[i] != 0)
{
evensAdd--;
sum += arr[i];
}
if (evensAdd == 0)
{
break;
}
}
return sum;
}
Using break will immediately jump to the end of the for loop and the return value will be set if in all cases.
EDIT: Check your compiler warnings, I'm pretty sure that every compiler gives a "Control may reach end of non-void function".
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i < size && evensAdd > 0; i++)
{
if (arr[i] % 2 == 0 && arr[i] != 0)
{
evensAdd--;
sum += arr[i];
}
}
return sum;
}
This will work but like #πάντα ῥεῖ said using vectors would be a better idea.
You can just stop the loop with set condition, which is in this case better style than breaking.
Working example!

Can you explain this code to me and why is work c++ prime numbers

This code is to find the prime numbers from 3 to n, n being an input. this code works perfect but I need to understand it much more clearly mostly the part within the nested for loop.
#include <iostream>
using namespace std;
int main ()
{
cout << "Please enter a number: \n";
int inputtedNumber;
cin >> inputtedNumber;
cout <<"the primes between 3 and that number are: \n";
int candidate = inputtedNumber;
for (int i=3; i<candidate; i++)
{
bool prime=true;
for (int j=2; j*j<=i;j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << "\n";
}
system("pause");
return 0;
}
thank you!
The inner loop looks at each number from 2 to the square root of i, to see if i is divisible by that number. If i is divisible by j, then i%j will be zero. If it finds a divisor, then we know it's not prime and can stop looking.
There's no need to go beyond the square root since, if there is a divisor larger than that, there must also be a corresponding divisor smaller than that, which will already have been found by this loop.
This line is key.
if (i % j == 0)
The if block is executed if i is divisible by j, which implies that i is not prime.
for (int i=3; i<candidate; i++) // for every i between 3 and candidate
{
bool prime=true;
for (int j=2; j*j<=i;j++) // for every j between 2 and the square root of i
{
if (i % j == 0) // if there is an i that is evenly divisible by j
{
prime=false; // set the flag
break; // break the inner loop
}
}
if(prime) cout << i << "\n"; // if i was a prime (no j's were evenly divisible), print it
}