C++ Prime Numbers program [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on a C++ program that determines and prints the prime numbers between 3 and an integer 'x' the user inputs. I'm assuming that I need a double nested loop for this, one to iterate from 3 to x and the other to check if the number is prime. I think it needs to do something like go from 2 to x-1? I'm just really not sure how to do this syntax-wise. Thanks for any help! :)
EDIT:
This is what I have:
#include <iostream>
#include <cmath>
using std::cout;
using std::endl;
using std::cin;
int main(){
int x;
int i;
int j;
cout << "Please enter an integer 'x' greater than 3: " << endl;
cin >> x;
if (x <= 3){
cout << "Please enter new value 'x' greater than 3: " << endl;
cin >> x;
}
for(int i=3; i<=x; i++){
for(j=2; j<i; j++){
if(i%j == 0)
break;
else if(i == j+1);
cout << i << endl;
}
}
return 0;
}
And I when I enter 10 as 'x' I get the output:
3
5
5
5
7
7
7
7
7
9
Can anyone tell me how to fix this?

Provided your X is small enough, you can use the Sieve of Eratosthenes to do it more efficiently. This is ideal for the "primes up to X" case since it maintains a memory of previously discarded primes. It does so by keeping a set of flags for each candidate number, all initially set to true (except for 1, of course).
Then you take the first true value (2), output that as a prime, and then set the flags for all multiples of that to false.
Then carry on with:
3;
5 (since 4 was a multiple of 2);
7 (since 6 was a multiple of 2 and 3);
11 (since 8 and 10 were multiples of 2 and 9 was a multiple of 3);
13 (since 12 was a multiple of 2);
17 (since 14 and 16 were multiples of 2 and 15 was a multiple of 3 and 5);
and so on.
Pseudo-code would be similar to:
def showPrimesUpTo (num):
// create array of all true values
array isPrime[2..num] = true
// start with 2 and go until finished
currNum = 2
while currNum <= num:
// if prime, output it
if isPrime[currNum]:
output currNum
// also flag all multiples as nonprime
clearNum = currNum * 2
while clearNum <= num:
isprime[clearNum] = false
clearNum = clearNum + currNum
// advance to next candidate
currNum = currNum + 1
Otherwise, you can do trial division as per your suggestion. The basic idea is to check each number from 2 up to the square root of your target number to see if it's a multiple. In pseudo-code, that would be something like:
def isPrime (num):
// val is the value to check for factor
val = 2
// only need to check so far
while val * val <= num:
// check if an exact multiple
if int (num / val) * val == num:
return false
// no, carry on
val = val + 1
// if no factors found, it is a prime
return true
The reason you only need to check up to the square root is because, if you find a factor above there, you would have already found the corresponding factor below the square root.
For example, 3 x 17 is 51. If you're checking the numbers from 2 through 50 to see if 51 is prime, you'll find 3 first, meaning you never need to check 17.

int main (char argv)
{
int tempNum = atoi(argv);
for (int i=3; i<=tempNum; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i)) {
cout << i << " ";
}
}
return 0;
}
Printing prime numbers from 1 through 100
Basically this, but modified

I find this one pretty fast and efficient
int main(){
for(int i=3; i<=X; i++)
if(IsPrime(i)){
cout<<i<<endl;
}
}
bool IsPrime(int num){
/* use commented part if want from 2
if(num<=1)
return false;
if(num==2)
return true;
*/
if(num%2==0)
return false;
int sRoot = sqrt(num*1.0);
for(int i=3; i<=sRoot; i+=2)
{
if(num%i==0)
return false;
}
return true;
}

Related

Kickstart 2022 interesting numbers

The question is to find the number of interesting numbers lying between two numbers. By the interesting number, they mean that the product of its digits is divisible by the sum of its digits.
For example: 459 => product = 4 * 5 * 9 = 180, and sum = 4 + 5 + 9 = 18; 180 % 18 == 0, hence it is an interesting number.
My solution for this problem is having run time error and time complexity of O(n2).
#include<iostream>
using namespace std;
int main(){
int x,y,p=1,s=0,count=0,r;
cout<<"enter two numbers"<<endl;
cin>>x>>y;
for(int i=x;i<=y;i++)
{
r=0;
while(i>1)
{
r=i%10;
s+=r;
p*=r;
i/=10;
}
if(p%s==0)
{
count++;
}
}
cout<<"count of interesting numbers are"<<count<<endl;
return 0;
}
If s is zero then if(p%s==0) will produce a divide by zero error.
Inside your for loop you modify the value of i to 0 or 1, this will mean the for loop never completes and will continuously check 1 and 2.
You also don't reinitialise p and s for each iteration of the for loop so will produce the wrong answer anyway. In general limit the scope of variables to where they are actually needed as this helps to avoid this type of bug.
Something like this should fix these problems:
#include <iostream>
int main()
{
std::cout << "enter two numbers\n";
int begin;
int end;
std::cin >> begin >> end;
int count = 0;
for (int number = begin; number <= end; number++) {
int sum = 0;
int product = 1;
int value = number;
while (value != 0) {
int digit = value % 10;
sum += digit;
product *= digit;
value /= 10;
}
if (sum != 0 && product % sum == 0) {
count++;
}
}
std::cout << "count of interesting numbers are " << count << "\n";
return 0;
}
I'd guess the contest is trying to get you to do something more efficient than this, for example after calculating the sum and product for 1234 to find the sum for 1235 you just need to add one and for the product you can divide by 4 then multiply by 5.

My C++ prime number identifier and prime factor finder has a bug [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm a beginner to C++ and this website, so any dumb mistakes are out of ignorance. For practice, I'm trying to write a program that identifies a prime number and gives a composite's prime factors if the user requests. The prime IDer works, but the prime factors do not. When I type in twelve as my number, it gives me the factors 2 3 and 5, and 12's prime factors are 2 2 and 3. What am I messing up? Here is the code. Don't mind the weird spaces or names.
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
//Printing factors help
void print(std::vector<int> const& factors)
{
for (int i = 0; i < factors.size(); i++) {
std::cout << factors.at(i) << ' ';
}
}
int main() {
//Restarting it
std::string again;
again = "Yes";
//Actual loop
while (again == "Yes") {
//Variable/vectors
std::string pfacts;
double input = 0;
double result = 0;
double looper = 2;
int looper2 = 2;
int printed = 0;
int printed2 = 0;
std::vector<int> factors;
std::vector<int> holders;
//Asking for number
std::cout << "Please enter your number.\n";
std::cin >> input;
double holder = input;
//Ratting out trolls
if (input == 0) {
std::cout << "Your number is neither.\n";
looper = 1000003;
}
if (input == 1) {
std::cout << "Your number is neither.\n";
looper = 1000003;
}
//Prime/composite loop
while (looper < 1000002 and input != 1 and fmod(result, 1) == 0) {
result = input / looper;
//Finding composite
if (fmod(result, 1) == 0 and printed == 0) {
std::cout << "Your number is composite.\n";
printed = 1;
looper = 1000003;
}
//Finding prime
else if (fmod(result, 1) != 0 and printed2 == 0) {
std::cout << "Your number is prime.\n";
printed2 = 1;
}
}
//Asking about factors
if (printed == 1) {
std::cout << "Would you like to know it's prime factors? (Please type Yes or No exactly)\n";
std::cin >> pfacts;
}
//Actually finding them
if (pfacts == "Yes") {
while (looper2 < 1000002) {
if (holder / looper2 == 0) {
factors.push_back(holder);
looper2 = 1000003;
}
if (looper2 < 1000002 and fmod (fmod(holder, looper2), 1) == 0 and looper2 % 2 != 0 or looper2 / 2 == 1) {
factors.push_back(looper2);
holder = holder / looper2;
}
looper2 = looper2 + 1;
}
//Printing them
print(factors);
std::cout << "\n";
}
//Again?
std::cout << "Do you need to input another number? (Please type, exactly: Yes or No)\n";
std::cin >> again;
}
}
You're just making a really simple thing more complex with that looper , printed stuff,
a good programmer is one which solves hard things in easy way.
So it is hard to understand for me to know exactly what you're doing in the code above at least not without enough comments.
So here is my solution, i am just providing the algorithm so you can write your own code and learn from it.
First note things below.
A prime number is a positive integer which has exactly two factors first is 1 and another is that number itself , so two is smallest prime number.
A number is also prime if it is not divisible from 2 to its square root, you should consider this fact for performance.
Now the algorithm:
Take the number in a variable num.
Check if it is positive integer greater then 1, if not then it is not a prime.
Take num's squareroot with help of sqrt() function in variable num as you don't need original num any more.
Now add one to num and take its absolute value.
Start a loop from i = 2 to num: you're starting from 2 because two is the smallest prime.
In every iteration check num % i == 0, if yes then it is not a prime and you break, otherwise don't do anything.
Now after the loop ends check if i == num, if yes that means you never broke the hence the number is prime and you're done, otherwise you broke the loop hence the number is not prime and you ask for prime factors.
Now again you start from j = 2 to num.
Now if num % j == 0, you print j and do num = num / j, otherwise you increment j.
I hope it is helpful. I didn't test it on an IDE, because I don't have one because I don't write c++ code anymore. Tell me if you find any bugs.

display the series and input digit count that if ...input n=900 then output will be 1 4 9 25 49 121 169 289 361 529 841 and count =3 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Help me out with my code or else a new one. Here in this code I didn't wrote the digit count module yet. I tried it to print the squares of prime numbers i.e., less than the given n number, and I figure out the output with same numbers as shown in the screenshot
#include<stdio.h>
void main()
{
int num, i = 1, j, count, s = 1;
clrscr();
printf("Enter Num value To Print Prime Numbers between 1 and Num: ");
scanf("%d", &num);
printf("Prime Numbers upto %d :\n \n", num);
while (i <= num)
{
if (s>num)
break;
count = 0;
for (j = 1; j <= i; j++)
{
if (i%j == 0) //checking whether num is dvisible by j
count++;
}
if (count == 2) //if num is divisible by 2 numbers,then it is prime
s = i*i;
printf("%d ", s);
i++;
}
printf("\n\n");
getch();
}
Output: 0 4 9 9 25 25 49 49 49 49 49 121 121 .......961
here are some of the problems with the posted code.
1) main() must always have an 'int' return type
2) if the '-Wstrict-prototype warning is enabled, then the declaration of main must be:
int main( void )
3) the function clrscr() is not defined, suggest using:
system( "cls" );
4) the function getch() is not defined, suggest using:
getchar();
For human readability and ease of maintenace, suggest:
only one variable declaration per line
indent code via spaces, perhaps after each opening brace and before each closing brace
the definition of a 'prime' number, as stated in the code, is not correct.
the correct definition:
"A number is a prime number if it is evenly divisible only by 1 and itself"
Problem is that when i is not prime s will print out the previous value stored in it. You can either clear s or put it in braces in if condition
while (i <= num)
{
if (s>num) //problem lies here
break;
count = 0;
for (j = 1; j <= i; j++)
{
if (i%j == 0) //checking whether num is dvisible by j
count++;
}
if (count == 2) //if num is divisible by 2 numbers,then it is prime
{
s = i*i;
printf("%d ", s);
}
//s = 0; //or use this if you don't want to use braces which is a bad programming style
i++;
}
Also, 1 is not a prime number so your expectd output should start from 4

Using char arrays to add together large numbers

I have an assignment in which I am supposed to
1.) Read in 2 char arrays of numbers
2.) add together the arrays, performing carry addition, carrying the tens place
3.) print out the newly added array.
I am also supposed to print an error if I need to carry on the last digit of the array (overflow)
so something like 99999999999999999999 +
1 =
________________________
ERROR
That's the part I'm having trouble with.
The above outputs something like "99999999999999999:0" so I have no idea what's going wrong.
I'll post my code, but please be nice :( I know it certainly isn't the most efficient, but I'm just trying to lay things out in a way that is easy for my brain to understand right now.
And yes, I HAVE to use char arrays. I guess it's to help us understand the ascii table.
#include <iostream>
using namespace std;
void InitNumber(char[]);
int AddArrays(char first[], char second[], char combined[]);
void OutputNumber (char[]);
const int LENGTH = 20; // global variable
int main()
{
char set1[LENGTH];
char set2[LENGTH];
char sum[LENGTH];
InitNumber (set1);
InitNumber (set2);
if(AddArrays (set1, set2, sum)) {
cout << "overflow!" << endl;
}
OutputNumber(sum);
}
void InitNumber (char list[])
{
int numberOfDigits;
cout << "Please enter the number of digits in the number: ";
cin >> numberOfDigits;
cout << "Please enter the digits in the number with the LEAST significant first: ";
for (int i = 0; i < numberOfDigits; i++) {
cin >> list [i];
}
for (int l=(numberOfDigits); l < LENGTH; l++) {
list [l] = '0';
}
}
int AddArrays(char first[], char second[], char combined[])
{
for (int h = 0; h < LENGTH; h++)
combined[h]= '0';
int overflow = 0;
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
cout << "currentSum = " << currentSum << endl;
if(currentSum / 10 == 0 )
combined[i] += currentSum;
else if (currentSum/10 !=0) {
if (i == LENGTH-1 && currentSum/10 !=0){
overflow = 1;
}
else{
combined [i] += currentSum%10;
cout << "current i: " << combined[i] << endl;
combined [i+1] += currentSum/10;
cout << "current i+1: " << combined[i+1] << endl;
}
}
}
return overflow;
}
void OutputNumber(char arrayOut[])
{
for (int l=LENGTH - 1; l >= 0; l--)
cout << arrayOut[l];
}
working input
input
6
1 2 3 4 5 6
7
1 2 3 4 5 6 7
output
00000000000008308642
Not-working output
input
20
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
1
1
output
999999999999999999:0
I'm going to reproduce small parts of your inner loop where you are carrying out the addition, in order to explain why your overflow detection is broken.
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
if(currentSum / 10 == 0 )
combined[i] += currentSum;
Here you're adding the corresponding pair of digits from the two numbers you're adding, and checking (in your particular style) if they overflowed. Try to remember this part, it's important. In order to check for overflow, you're only checking the result of adding the pair of digits from the two large numbers you're adding.
else if (currentSum/10 !=0) {
This is a completely useless check. You can only get here if the division is known to produce a non-zero result. This if() can be removed completely. Now, the relevant part of your code is
combined [i] += currentSum%10;
combined [i+1] += currentSum/10;
Do you see the problem yet?
Your approach is, once overflow is detected, is to increment the next higher order digit in the result.
Unfortunately, on the next loop iteration, in order to check for carry over, you're just checking the sum of the next corresponding digit pair, from the two large numbers you're adding. The carry-over you're saving here is going to get completely ignored.
Say your numbers are two digits long max, rather than 20, and you entered the numbers 99 and 1.
On the first iteration, you'll add 9 and 1, save 0 as the first digit, and add 1 to the second digit in the sum.
On the second iteration, you'll add 9 and 0, and, given your logic above, conclude that nothing overflowed.

C++ program to find the largest palindrome which is product of two two digit numbers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have seen this, but this is not what I am looking for.
The problem is same that is to find the largest palindrome which is the product of two three digit numbers.
Since my program was not working so I made a little change, instead of finding the largest palindrome which is the product of two three digit numbers I have written the program to find the largest palindrome which is the product of two two digit numbers.
Kindly see the program:
#include <iostream>
using namespace std;
int main() {
int i, j, n, s, m, w;
for (i = 99; i > 9; i--) {
for (j = 99; j > 9; j--)
n = i * j;
s = n;
while (n != 0) {
w = 0;
m = n % 10;
w = w * 10 + m;
n = n / 10;
}
if (s == w)
cout << s << endl;
break;
}
return 0;
}
The problem with this program is that it is neither showing any error nor giving any result.
So kindly help me to find the problem in my program.
Right now you are missing the curly braces for the j-loop. The current code is doing 99! * i.
Then you would have to focus on storing the largest palindrome value instead of just printing all those values to the screen (this is considering your implementation, it is not the most efficient one by any means).
Some modified version of your code:
#include <iostream>
using namespace std;
int main() {
int max_product = 0;
for (int i = 99; i > 9; i--) {
for (int j = i; j > 9; j--) {
int product = i * j;
if (product < max_product)
break;
int number = product;
int reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
if (product == reverse && product > max_product) {
max_product = product;
}
}
}
cout << "Solution: " << max_product << endl;
return 0;
}
You have various problems:
Need one more pair of {, }. After the for-loop of j. The only instruction the for-loop of j is executing is: n = i * j; with the braces the rest of the instruction (testing if it's a palindrome) are out of the loop.
the variable w the reverse of the number to test for palindrome is reset his value to 0 in every execution of while (n != 0) loop resulting in incorrect reverse value (and never find the palindrome).
The max palindrome product of 2 two digits number don't have to be the first one found with this 2 for-loop, eg: suppose that there is 2 valid solutions i = 98, j = 2 and i = 70, j = 65 in this case i*j would be in first solution = 196 in the second = 4550 and when you found the first you could not stop the search. In your code using the break don't do what I think you are waiting for (stop the search), only stop the search with the actual i value.
Some notes about the modified code:
The two for-loop don't need to be from 99..9, in this case you are testing a lot of product two times (eg: 98*99, are testing when i == 98 and j == 99 and i == 99 and j == 98), you could restrict j to be always less or equal to i.
Using max_product to maintain the maximum palindrome product found. And use that info in the inner loop (if (product < max_product)) for early exit when no better solution could be found.