C++ nested loop prime number - c++

I have a question that I couldn’t solve , I worked hard and didn’t have a total solution
I need to type a number of soldiers and check out if the
serial numbers product = the number of soldiers
and
check if one of the serial numbers is PRIME.
As a result I need to print the 2 serial numbers that bring me the product once
For example:
Number = 20
I need to print
2 10
4 5
Number = 120
I need to print
2 60
3 40
5 24
6*20 Cant be printed because none of them is prime number
and so on
Number = 48
I need to print
2 24
3 16
4*12 Cant be printed because none of them is prime number
And so on
I did everything alright except finding if one of the numbers is prime
the code is :
int armysize;
cout << "Please type how many soldiers do you have in your army:" << endl;
cin >> armysize;
int serialnumproduct = 0;
for (int soldiernum = 2; soldiernum < sqrt(armysize); soldiernum++)
{
for (int nextsoldier = 2; nextsoldier <= armysize/2; nextsoldier++)
{
serialnumproduct = soldiernum * nextsoldier;
if (serialnumproduct == armysize && soldiernum != nextsoldier)
cout << soldiernum << " * " << nextsoldier << " = " <<
serialnumproduct << endl;
}
}
return 0;

A function such as this one should tell you wether a number is prime or not. You need to make sure you are dealing with numbers that can fit in an int on your machine, or update the code
bool IsPrime (int ninteger)
{
bool prime (true);
for(auto i = 2 ; i<ninteger ; ++i)
{
if (ninteger%i == 0)
prime = false;
}
return prime;
}

Basically what you need is a function to show if soldiernum is a prime number or not. I used a prime_test() function and used it on line 34 as an if() statement, so the code see if it should use the soldiernum or not.
This was the result:
Please type how many soldiers do you have in your army:
400
2 * 200 = 400
5 * 80 = 400
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
bool prime_test (int num)
{
bool prime (true);
for(int i = 2 ; i<num; ++i)
{
if (num%i == 0)
prime = false;
}
return prime;
}
int main(){
int armysize;
int count=2;
bool isPrime = true;
cout << "Please type how many soldiers do you have in your army:" << endl;
cin >> armysize;
int serialnumproduct = 0;
for (int soldiernum = 2; soldiernum < sqrt(armysize); soldiernum++){
for (int nextsoldier = 2; nextsoldier <= armysize/2; nextsoldier++)
{
serialnumproduct = soldiernum * nextsoldier;
if (serialnumproduct == armysize && soldiernum != nextsoldier)
if(prime_test(soldiernum)==true) {
cout << soldiernum << " * " << nextsoldier << " = " <<
serialnumproduct << endl;
}
}
}
return 0;
}

Related

How do i sum all numbers using loop?

For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements) the index of this number starts from 1 by this it means​ that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;
int i, n, result = 0;
cout << "Input number to sum: ";
cin >> n;
// Finding result
for (i = 0; i <= n; i++){
if (i % 2 == 0) {
result +=i;
} else {
result += i * 5;
}
}
// Make last number have equal sign "1+6+7+12 = 36"
for (i = 0; i <= n; i++){
if (i == n) {
cout << i..?? << "=";
} else {
cout << i..?? << "+";
}
}
// Print result out
cout << result;
return 0;
}
Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
int value = i % 2 == 0 ? i + 1 : i + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>
int main()
{
int n;
std::cout << "Input number to sum: ";
std::cin >> n;
auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };
int result = 0;
int value = 0;
for (int i = 0; i < n; i++)
{
value += update(i);
result += value;
}
std::cout << '\n';
for (int i = 0, value = 0; i < n; i++)
{
value += update(i);
std::cout << (i > 0 ? " + " : "") << value;
}
std::cout << " = " << result;
}
Testable here.
I agree with molbdnilo's answer. However the algorithm some changes.
The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)
while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;
int main()
{
int i, n, result, value = 0;
cout << "Input number to sum: ";
cin >> n;
for (i = 0; i < n; i++)
{
value = i % 2 == 0 ? value + 1 : value + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
return 0;
}
Testable here

How do I limit the amount of numbers I have in a row?

I'm attempting to list a set of prime numbers from a lower bound to an upper bound limiting the number of prime numbers in a row to 8. Though I have done the first part, I can't get them to list in rows with only 8 prime numbers per row.
#include <iostream>
enter code here
int main()
{
int low, high, i, flag, j;
cout << "Enter two numbers(intervals): ";
cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: ";
while (low < high)
{
flag = 0;
for (i = 2, j = 1; i <=low/2; +ii, ++j)
{
if (j == 8)
{
cout << "\n";
j = j - 7;
}
else if (low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";
++low;
}
return 0;
}
It works for the first row, then everything else seems to start listing rather than being in a row.
Output: Enter two numbers(intervals): 1
200
Prime numbers between 1 and 200 are: 1 2 3 5 7 11 13 17
19
23
29
31 ...
It's a little late, but I said I'd do it. My suggestions:
#include <iostream>
//enter code here
using std::cin;
using std::cout;
int main()
{
int low, high, count, i;
bool flag; // bools are more suited to being flags
cout << "Enter two numbers(intervals): ";
cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: ";
count = 1; // I replaced j with this for ease of reading
while (low < high)
{
flag = true;
// using break in loops is not recommended, and you already have a flag
for (i = 2; i <= low / 2 && flag; ++i)
{
if (low % i == 0)
{
flag = false;
}
}
if (flag)
{
cout << low;
if (count == 8)
{
cout << std::endl;
count = 1;
}
else
{
cout << " ";
++count;
}
}
++low;
}
return 0;
}
Your code divide not every 8 prime numbers, but every 8 attempts of dividing a number during search for prime number. So any prime that is 8 or more values away from previous will generate a line break. Consider following fix:
#include <iostream>
using namespace std;
int main()
{
int low, high, i, flag, j;
cout << "Enter two numbers(intervals): ";
cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: ";
j = 0;
while (low < high)
{
flag = 0;
for (i = 2; i <=low/2; ++i)
{
// Removed here
if (low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
++j; // Added here
cout << low << " ";
}
if (j == 8) // and here
{
cout << "\n";
j = j - 8;
}
++low;
}
return 0;
}
By the way, you should end a search when reaching square root of low, not low / 2. The loop will be much faster.

Palindromes And Project Euler C++ Version -Tips

Can Anyone Tell Me What's Wrong In My Code?
Thank you :)
// A palindromic number reads the same both ways.
// The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
#include <iostream>
using namespace std;
int main()
{
int x = 2;
int product;
int n, digit, rev = 0;
int greatest = 0;
for(int i = 2;i<100;i++){
product = x * i;
n = product;
cout << x << " * " << i << " = " << product << endl;
do
{
digit = product % 10;
rev = (rev * 10) + digit;
product = product / 10;
} while(product != 0);
cout << " The reverse of the number is: " << rev << endl;
if(n == rev){
cout << "Therefore Palindrome" << endl;
if(rev > greatest){
cout << "REV Greater Than Greatest Palindrome" << endl;
greatest = rev;
}
}
if(i == 99){
if(x < 99){
x++;
i = 1;
cout << "Go For The Next Loop" << endl;
}
}
}
cout << "The Greatest Palindrome Number Is " << greatest << endl;
return 0;
}
Several things:
You should be counting down from 999 thru 100.
You should be using two loops for the two factors of your product
rev should be initially zero before each entrance into your inner do-while loop
The results would look something like this, with all but the detected palindromes and final result being output (the amount of worthless noise in your output is mind-bending)
#include <iostream>
using namespace std;
int main()
{
int product;
int n, digit, rev = 0;
int greatest = 0;
for(int i = 999;i>=100; --i)
{
for (int j =999; j>=100; --j)
{
product = j * i;
n = product;
rev = 0;
do
{
rev = (rev * 10) + (product % 10);
product /= 10;
} while(product != 0);
if(n == rev)
{
cout << "Palindrome : " << i << " * " << j << " = " << n << endl;
if(rev > greatest)
greatest = rev;
}
}
}
cout << "The Greatest Palindrome Number Is : " << greatest << endl;
return 0;
}
This will conclude the correct answer you seek.
Faster
Optionally, you can squeeze better performance out of this by understanding a few additional details:
The task is to find the largest palindrome, not just the longest palindrome. Therefore, once you find one, any product, palindrome or not, that is a smaller magnitude than the current largest palindrome is pointless to even check and the inner loop can be terminated (thus the reason you're counting down).
A little number crunching will allow you to conclude that at least one of the factors must be divisible by 11. I won't cover why, but do the math, it's true. Therefore, you can make one of your loops a count-down from the largest 3-digit multiple of 11 (990) to 100, in steps of (-11).
The result looks like this:
#include <iostream>
using namespace std;
int main()
{
int greatest = 0;
for(int i = 999;i>=100; --i)
{
for (int j =990; j>=100; j-=11)
{
int product = j * i;
if (product < greatest)
break;
int n = product;
int rev = 0;
do
{
rev = (rev * 10) + (product % 10);
product /= 10;
} while(product != 0);
if(n == rev)
{
cout << "Palindrome : " << i << " * " << j << " = " << n << endl;
if(rev > greatest)
greatest = rev;
}
}
}
cout << "The Greatest Palindrome Number Is : " << greatest << endl;
return 0;
}
Output
Palindrome : 995 * 583 = 580085
Palindrome : 993 * 913 = 906609
The Greatest Palindrome Number Is : 906609

C++ How to use a function returning a Boolean Value to determine prime numbers

I am suppose to make a program that asks a user to input an integer 'n' between 1 and 100, and have an input validation loop. The program will then calculate the first 'n' prime numbers and print them. So I figured out how to calculate the prime numbers and display them, 10 numbers per line, all in the main function. What I have to do is to have a function called isPrime() that takes an integer and returns true if it is prime and false otherwise. I'm not sure how to go about this. This is the code I have for function main().
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
int count = 0;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
while (number < 0 || number > 100)
{
cout << "Invalid number." << endl;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
}
cout << "The first " << number << " primes: \n" << endl;
for (int i = 2; number > 0; ++i)
{
bool isPrime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
cout << endl;
system("pause");
return 0;
}
Any help is good, thanks in advance.
You seem to be testing i % j for every j lower then i. But if you tested for j = 3 then you can exclude all multiples of 3. When a number can't be divided by 3 it can't be divided by 6. This will improve performance.
You can also implement the AKS primalty test https://en.wikipedia.org/wiki/AKS_primality_test
This might be a little more work. I don't know the details of this test but it is deterministic and works on all numbers.
If you want a function bool isPrime(int number) you can just extract this code from your main method, it looks something like this:
bool isPrime(int number){
for (int j = 2; j < number/2; ++j)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
The for loop in the main function will be something like:
for (int i = 2; number > 0; ++i)
{
if (isPrime(i))
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}

Classifying digits of an integer value

I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks