explain this prime number program [C] - c++

#include<stdio.h>
main()
{
int n;
int a,b,flag=1;
scanf("%d",&n);
for(a=2; a<=n; a++)
{
if(n % a == 0)
{
printf("not prime");
flag = 0;
break;
}
}
if(flag == 1)
{
printf("is prime");
}
getch();
}
when you use this for loop
for(a=2; a<=n; a++)
when user will input 2 it will print "not prime:
if you put that if(flag == 1) statement inside the for loop it doesn't print anything when the user inputs 2. Why is that if(flag == 1) outside that for loop
#include<stdio.h>
main()
{
int i, num, flag = 1;
scanf("%d",&num);
for(i=2; i<=sqrt(num); i++)
{
if(num%i==0)
{
printf("not prime");
flag=0;
break;
}
}
if(flag==1)
{
printf("is prime");
}
getch();
}
when you will use square root in for loop
for(i=2; i<=sqrt(num); i++)
then it give correct result
if you enter 2 then it prints 2 is prime number
WHY ?
and what is flag variable how does it work ?

The problem is that this line is wrong:
for(a=2; a<=n; a++)
It should be this:
for(a=2; a<n; a++)
Because n is always divisible by itself it will mean that n % a == 0 when a is n. This does not mean the number is not prime. A prime is exactly divisible by 1 and itself, but no other integer.
When you change the test to a <= sqrt(num) you also happen to fix this bug.

for(a=2; a <= n; a++)
should be
for(a=2; a < n; a++)
//^ difference
Also, when you use sqrt(n), you better write this outside the loop to improve performance:
int m = sqrt(n); //store the result in int type
for(a=2; a <= m ; a++)
In this way, you calculate sqrt(n) just ONCE, instead of in every iteration, and instead of relying on the compiler to optimize this step.

Related

Difficulties for printing pyramid pattern of numbers

1
232
34543
I have divided the pattern in two parts. first part is prints increment numbers and second part prints decrement numbers.
1st loop is for printing rows.
2nd loop is for printing spaces. 3rd
loop is for printing increment numbers.
4th loop is for decrement
numbers.
Code works fine up-to the 3rd loop. But the 4th loop is not giving the required output.
#include<stdio.h>
int main()
{
int i,j,n;
scanf("%d",&n);
/*Print row*/
for(i=1;i<=n;i++)
{
/*Printing Spaces*/
for (j = 1; j <= n-i; j++)
{
printf(" ");
}
/*Printing increasing number values*/
for ( int num = i; num <= 2*i-1; num++)
{
printf("%d",num);
}
/*Printing decreasing numbers value*/
for ( int num = 2*i-2; num <= i-1; num++)
{
printf("%d",num);
}
/*New line*/
printf("\n");
}
return 0;
}
Output is :
10
23
345
Welcome to SO.
Your first error was on the your counter on your 4th loop. Your loop should display decreasing numbers but you keep incrementing your counter (that you use to print too).
First error, decrease the counter in the 4th loop.
Second error is your condition on this first loop. You decrease a counter so your condition "While my counter is under a value" can never be false if the counter, at start of the loop, is already before the value. So you have to replace <= by >=.
And after test you will see that i-1 always print one number too far of remove your -1.
Here is your code corrected :
#include<stdio.h>
int main()
{
int i,j,n;
scanf("%d",&n);
/*Print row*/
for(i=1;i<=n;i++)
{
/*Printing Spaces*/
for (j = 1; j <= n-i; j++)
{
printf(" ");
}
/*Printing increasing number values*/
for ( int num = i; num <= 2*i-1; num++)
{
printf("%d",num);
}
/*Printing decreasing numbers value*/
for ( int num = 2*i-2; num >= i; num--)
{
printf("%d",num);
}
/*New line*/
printf("\n");
}
return 0;
}

finding a number is prime or not

the code is showing wrong results...it is showing 15,21 and many other odd numbers as prime but they are not...how to fix the problem?..what code should I write in main section[inside int main()]?
#include<bits/stdc++.h>
using namespace std;
#define M 1000000
bool marked[M];
bool sieve(int n)
{
for (int i = 3; i * i <= n; i += 2)
{
if (marked[i] == false)
{
for (int j = i * i; j <= n; j += i + i)
{
marked[j] = true;
}
}
}
}
bool isPrime(int n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
return marked[n] == false;
}
int main()
{
int i,j,k,n,m;
cin>>n;
for(i=0; i<n; i++)
{
cin>>m;
if(isPrime(m))
cout<<"prime"<<endl;
else
cout<<"N"<<endl;
}
}
Is the wrong answer coming due to not properly using or calling functions?.....in this case what should be done.....
My guess is that, since you never call the sieve function, your marked array never gets filled. Since marked is not dynamically allocated, it is zeroed out within your program. Hence, in your isPrime function, all odd numbers will cascade through your if statements and then hit the part where marked[n] == false which would return true since marked[n] is 0 for all of its entries, which is equivalent to the boolean false.
You might want to figure out where it would be best to run the sieve function.
You have wrong increment here:
for (int j = i * i; j <= n; j += i + i)
You need to increase j by i, but you actually increase in by 2*i. Anyway I agree with the previous answer that you never call sieve.

infinite loop when user enter a large number

I'm writing a function called largestTwinPrime where it takes in 2 numbers and finds the largest twin prime number between the two. My program works however when the user enters a large enough number the program becomes an infinite loop. For example:
largestTwinPrime(0, 15485661) would give me this error "Program exceeded its time limit and was stopped (possible infinite loop)".
largestTwinPrime(1, 18) would output 17.
This is the code I have and thanks for the help!
(isPrime)
int isPrime(int num){
if(num <= 1) return 0;
for (int i = 2; i * i <= num; i++){
if (num % i == 0) return 0;
}
return 1;
}
(isTwinPrime)
bool isTwinPrime(int n){
if(n <= 1) return 0;
if(isPrime(n+2)==true && isPrime(n)==true){
return 1;
} else if(isPrime(n-2)==true && isPrime(n)==true){
return 1;
} else{
return 0;
}
}
(largestTwinPrime)
int largestTwinPrime(int a, int b){
int answer=0;
while(a <= b){
for(int i = a; i <= b; i++){
if(isTwinPrime(i)== true){
answer = i;
}
}
a++;
}
if(answer==0) return -1;
else return answer;
}
Your code has a very poor complexity. Your code is invoking isTwinPrime O(n2) times which totals over O(n2.5). This makes it look like an infinite loop:
while(a <= b){ // O(N) iterations
for(int i = a; i <= b; i++){
// times O(N) = O(N**2)
if(isTwinPrime(i)== true){ // The call is over O(sqrt(N))
answer = i;
}
}
a++;
}
The correct code is:
int largestTwinPrime(int a, int b){
int answer=0;
if (b < 5) return -1;
// A twin prime is odd, so go over odd values.
if (b %2 == 0) b--;
for(int i = b; i >= a; i-=2){
if(isTwinPrime(i))
return i;
}
return -1;
}
Complexity is lower by a factor of O(N).
EDIT
Also, your isPrime is inefficient. Better to fill a vector of primes below sqrt(N) (using the Sieve of Eratosthenes), and use that to speed up the validation of primes.

Printing the 1000th prime number

#include <iostream>
using namespace std;
int main(){
int ctr = 0;
int count = 1; //Counts the nth prime number
int num = 3;
int div = 2; //Potential factors of the number
while(count <= 1000){
while(div < num){
if(num%div == 0){
ctr += 1; //If ctr is equal to 0, then num is prime
}
div += 1;
}
if(ctr == 0){ //If num is prime, count increases by 1
count += 1;
}
num += 1;
}
cout << num;
}
This is the code that I made to output the 1000th prime number. However, there must be something wrong with my program since it does not output 7919, which is the 1000th prime number.
It usually helps to refactor code like this into functions that have a clearly defined and testable behavior. For instance, the inner part of your code is a 'isPrime' function, and if you define it like this:
bool isPrime(int n) {
int div = 2; //Potential factors of the number
while (div < n) {
if (n % div == 0) {
return false;
}
++div;
}
return div == n;
}
It is easy to test, either through unit testing, or just manually checking if isPrime() works ok.
That makes the rest of the code more easy to write (and more importantly, read):
int primeCount = 0;
int n = 1;
while (primeCount < 1000) {
if (isPrime(n++)) {
++primeCount;
}
}
--n;
std::cout << n << std::endl;
As for why your code doesn't work. You should debug it. Go through line by line and see where it deviates from your expectations. Start out with finding the 3rd prime number, and not the 1000th.
Your isPrime part does not do what it is supposed to. Finding out why isn't hard, and you should definitely do that as a debugging-exercise, and not go with an easy answer from stackoverflow.
#include <stdio.h>
int main(){
int ctr = 0;
int count = 1; //Counts the nth prime number
int num = 3;
int div = 2; //Potential factors of the number
while(count <= 1000){
while(div < num){
if(num%div == 0){
ctr += 1; //If ctr is equal to 0, then num is prime
}
div += 1;
}
if(ctr == 0){ //If num is prime, count increases by 1
count += 1;
}
num += 1;
ctr=0;
div=2;
}
printf("%d",num);
}

C++ finding all prime numbers from 1 to a number entered

So the point is to have the program find and list all prime numbers between 1 and the number you enter. I'm using number_test as the number tested for prime, and divisor and the number to divide by.
I'm not sure what's wrong, as to me it looks functionally the same as the program posted here: Printing prime numbers from 1 through 100
with some minor changes (inputting a number, changing "i" to less than the number entered).
I've been looking for the past three or four days, and I haven't found anything that really answers this question fully, to the degree I need for class. Any help is much appreciated.
#include iostream
#include conio.h
using namespace std;
void main(void){
//Declare variables
int number_entered;
//Get inputs
cout << "This program lists all prime numbers from 1 through a positive number entered."
<< endl;
cout << "Please enter a positive integer."
<< endl;
cin >> number_entered;
cout << "Displaying all numbers from 1 to " << number_entered
<< endl
<< "Press any key to continue..."
<< endl;
getch();
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
getch();
}
You should use the Sieve of Eratosthenes to compute the primes less than n. Begin by making a list of all numbers from 2 to the maximum desired prime n. Then, at each iterative step, the smallest remaining number that hasn't yet been considered is output and all of its multiples are crossed off the list.
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve(p)
output p
for i from p*p to n step p
sieve[i] := False
This O(n log log n) algorithm is very fast; you should be able to compute the 78498 primes less than a million in less than a second.
A simple C++ Program to find the "N" prime numbers.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
Just a small suggestion. Since prime numbers are odd, even numbers can be left out.
For example, in below loops, i and j increase by 2 (i +=2) instead of by 1 (i ++).
for (int i=3;i<=numberByUser; i+=2){
for (j=3;j<=i;j +=2){
if (i%j==0){
break;
}
}
i think in your answer any way one time the loop will terminated(i am talking about the loop checking the whether it is prime or not)once it comes out you don't know whether it made the break or not.So try to make a flag variable and check outside.I ope that will work
for(n=lower+1; n<upper; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
printf("\n\n\t\t\t%d", n);
}
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
The above code will not show you the prime numbers, it will just show you the number you entered if/when you run into a divisor that is not a factor of the number. For example, if you enter "9", you will start at 2, which is not a factor of 9, so you will show "9" (incorrectly) as a "prime", when it is not.
The easiest method for testing if a number is a prime is by checking all prime numbers below it's square root to see if they are factors of the given number. If none of them are (then none of the non-prime numbers below the given number will be either), the number is a prime number. If it has at least one prime factor less than or equal to it's square root, it is not prime.
Since you are looking to show all primes in a range of [0, X], you can simply check your list of factors as you go along (or do it in reverse, which is effectively what the Sieve of Eratosthenes does).
When my point was like your one, I wrote this code, it worked. Hope it will help you.
#include <cstdio>
#include <vector>
using namespace std;
vector <int> sn;
bool isPrime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return true;
}
if (!(n % 2)) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (!(n % i)) {
return 0;
}
}
return 1;
}
void primeNumbers(int k) {
sn.push_back (2);
int i = 3, j = 1;
for ( ; j < k + 1; i += 2 && j++) {
if (isPrime(i)) {
sn.push_back(i);
}
}
}
int main() {
int i, k;
scanf("%d", &k);
primeNumbers(k);
for (i = 0; i < sn.size(); i++) {
printf("%d ", sn[i]);
}
return 0;
}
int getNumberOfPrimes(int N) {
bool *numbers = new bool[N-1]();
for (int i = 2; i <= N/2; ++i) {
if (numbers[i-2] == true) continue;
for (int j = i+i; j <= N; j = j+i) {
numbers[j-2] = true;
}
}
int count = 0;
for (int i = 0; i < (N-1); ++i) {
if (numbers[i] == false) ++count;
}
delete []numbers;
return(count);
}
Man I guess I have the simplest methode of this all. Hope it works for you!
#include < iostream >
using namespace std;
int main()
{
int n, i, j
cin>>n; //The max limith
for(i=2; i<=2; i++)
{
for(j=1; j<=i/2; j++)
if(i%j!=o)
cout<<i;
}
return 0;
}
If a number has divisors, at least one of them must be less than or equal to the square root of the number. When you check divisors, you only need to check up to the square root, not all the way up to the number being tested.