How to make program of prime numbers series from 1-100 in C++.
The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie. Prentice Hall, Inc., 1988. ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).
int n; cin>>n; for(int i=2;i<=n-1;i++) if(n==2) Cout<<"Prime Number"; else if(n%i==0) cout<<"Entered Number is not a prime no"; else cout<<"prime number"; i think the above code should work out for any given number.try this out!
I am yet to learn C++ but i hope this one written in C should help u-it generates prime numbers from 2 to your specified limit...for your case 100: #include <stdio.h> #include <conio.h> #include <math.h> int main () { int n,x,y,c,a; n=2; while(n<1000) { y=1; a=0; c=0; do{ x=sqrt(n); if((n%y)!=0) c=0; else a=a+1; /*a counts the number of times n is successfully divided*/ y++; }while(y<=x); if(c==0&&a==1) /*a=1 makes sure 1 is the only divisor that successfully divides n*/ printf("%i\t",n); n++; } getch(); return 0; }
This program works by induction, it starts printing 2 and storing 2 as a "known prime" on the array v, then checks if 3 is a multiple of any of the known primes, and if it isn't, 3 is a prime, it's printed, added to the list of known primes, and so on with 4, 5, 6... n was fixed as 100, but you can easily change its value or receive it as input. #include <iostream> using namespace std; int main() { unsigned long long n, i, j, cnt; n=100; unsigned long long v[n]; cnt=0; for(i=2;i<=n;i++) { for(j=0;j<cnt;j++) // {if((i%v[j])==0) break;} // if n isn't a multiple of any v[j] if(j==cnt) //then do this: {cout<<i<<endl; v[cnt]=i; cnt++;} } return 0; }
all of the above are correct.. but slow.The whole way of thinking is, every number has a divisor smaller or equal than its square root, so you have to loop over the diastema [2,sqrt(n)].This solution has a compexity of (n*sqrt(n)) slightly smaller than the O(n^2) proposed aobve.The significant improvement is to use the following theorem "Every number has at least one prime divisor" so you start with an array containing 2 and you start looping into the diastema [2,p] where p is the limit, once.For every number you find you check if it is divided by any of the numbers into the array, if not then it is a prime number.The pseudocode that implements this idea is the following. stack array[p] for(i=0 to p): for(j=0 to array.size): if(my_number mod array[j]==0) break; end of loop if(j==array.size) array.push(my_number) end of loop export result very brief and not a good code but i think it's kinda clear.If you are using c++ it's a good idea to use the stl stack in order to quickly use elements,otherwise an array would do. I have no idea what the average complexity of the algorithm is, it depends on the number of prime numbers.
Join our real-time social learning platform and learn together with your friends!