I'm trying to write a program that finds the prime factors for a number and print them
#include<iostream>
using namespace std;
void primeFactors(int num);
int main()
{
int num =0;
cout<<"plese input a positive integer: "; cin>>num;
primeFactors(num);
return 0;
}
void primeFactors(int num)
{
int fac=2;
while (num>1)
{
if (num%fac == 0)
{
cout<<fac<<" ";
num=num/fac;
}
else
{
fac++;
}
}
}
Example for console output:
please input a positive integer: 2700
2 2 3 3 3 5 5
I want to get an exponential notation for the output, for example: 2^2 x 3^3 x 5^2
Any ideas how can I achieve that? thanks
Try this
void primeFactors(int num)
{
int fac = 2;
while (num > 1)
{
if (num % fac == 0)
{
cout << fac << "^"; //print the base first
num /= fac;
int pow = 1;
while (num % fac == 0) //get the power of current base
{
num /= fac;
pow++;
}
cout << pow; //print out the power, now we have fac^pow printed
//if not the last factor, print a multiplication symbol
if (num != 1)
cout << " x ";
}
else
{
fac++;
}
}
}
Related
I'm trying to find the prime factors of any given number through this code. This code is working perfectly for small numbers but for larger numbers(like 12345678), the program is not terminating. What's wrong??
using namespace std;
bool isPrime(int i)
{
for(int k=2;k<i;k++)
{
if(i%k==0)
{
return false;
}
}
if(i==1)
{
return false;
}
return true;
}
int main()
{
int n;
cout<<"Enter number"<<endl;
cin>>n;
for(int i=2;i<n;i++)
{
if(isPrime(i))
{
int x=n;
while(n%i==0)
{
cout<<i<<endl;
n=n/i;
}
n=x;
}
}
if(isPrime(n))
{
cout<<n<<endl;
cout<<1<<endl;
}
return 0;
}
You have a pretty good prime factoring algorithm here, except that you have overthought a few bits. The check if i is prime is only needed because you keep restoring n after you divide out the prime factors you find.
Remember that if you take your N and then divide all of the 2 factors out, then no even number is going to be a divisor of the remainder. In the same fashion, if you divide out the 3 factors, then no number divisible by 3 is going to be a divisor of the remainder.
Or in other words: If you count up from 2 and divide out all the divisors, then every divisor you find (in the remainder of N) must be a prime - because in order for a non-prime to be a divisor, that numbers prime factors must also be divisors, but all smaller primes have already been divided out.
Using that logic, I have cut a few superfluous parts of your algorithm out:
void printPrimes(int n)
{
for (int i = 2;i < n;i++)
{
//if (isPrime(i))
//{
//int x = n;
while (n % i == 0)
{
cout << i << endl;
n = n / i;
}
//n = x;
//}
}
//if (isPrime(n))
//{
cout << n << endl;
//}
}
If we clean that a bit, and change the outer loop condition a bit (so that the largest prime won't have to be printed after the loop), we end up with this:
void printPrimes(uint64_t n)
{
for (int i = 2;n > 1;i++)
{
while (n % i == 0)
{
cout << i << endl;
n = n / i;
}
}
}
Edit:
My point here was to point out that OP already got a pretty close to a good algorithm on his own (and for the size of number he posted this works really well), but as pointed out in comments it can still be done better. For example like this:
void printPrimes(uint64_t n)
{
while (n % 2 == 0)
{
std::cout << 2 << '\n';
n = n / 2;
}
for (uint64_t i = 3;i * i <= n;i += 2)
{
while (n % i == 0)
{
std::cout << i << '\n';
n = n / i;
}
}
if (n > 1)
std::cout << n << '\n';
}
I am trying to find a reversed number and check that it is a palindrome or not from a different approach but I was getting a right reversed number up to two digits and if the digits are more than two then I am getting wrong output. I cannot understand why is this so as I think my code is right.
below is the code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, rem, t, add;
cin >> t;
while (t--) {
int total = 0, count = 0, i = 1, quo = 0;
cin >> num;
quo = num;
while (quo > 9) //count determiner
{
quo = quo / 10;
++count;
}
while (count >= 0) //reverse number saved in total
{
int den = pow(10, i);
rem = (num % den);
add = rem / pow(10, i - 1);
total = total + (add * pow(10, count));
++i;
--count;
}
if (total == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
please help me to know where I am going wrong in this code.
I don't understand your code. so i assumed by myself and wrote code.I assume that there will be no negative number and if there will be then i rid off negative sign. please provide desire output for negative number.
#include <iostream>
using namespace std;
int main()
{
//int num, rem, t, add;
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int num = abs(n);
if (n < 0)
{
n = abs(n);
}
int res{ 0 };
while (n > 0)
{
res *= 10;
int rem = n % 10;
res += rem;
n /= 10;
}
if (res == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
ouptut of above code:
4
-191
Palindrome
232
Palindrome
123
Not a Palindrome
561
Not a Palindrome
Your code to reverse a number is very convoluted, as it uses pow (a floating point function) to get each digit. This is totally unnecessary if you look for the pattern of how to reverse an integer.
Simple addition, multiplying by 10, and modulus is all that's necessary to do this. Note that I created a function, so that it is easy to follow:
#include <cmath>
#include <iostream>
int reverse_int(int num)
{
int total = 0;
// take care of negative by using absolute value
int tempNum = abs(num);
while (tempNum > 0)
{
total = (total*10) + (tempNum % 10);
tempNum /= 10;
}
return (num < 0)?-total:total;
}
int main()
{
int num = 1234321;
if ( num == reverse_int(num))
std::cout << num << " is a palindrome\n";
else
std::cout << num << " is not a palindrome\n";
int num2 = 123;
if ( num2 == reverse_int(num2))
std::cout << num2 << " is a palindrome\n";
else
std::cout << num2 << " is not a palindrome\n";
}
Output:
1234321 is a palindrome
123 is not a palindrome
The loop is very simple if you follow what is going on:
number = 123 (Assume this is our number)
total = 0;
Loop while (number > 0):
First iteration:
total = (total * 10) + (number % 10) --> (0 * 10) + (0 % 3) --> 3
number /= 10 --> 12
Second iteration:
total = (total * 10) + (number % 10) = (3 * 10) + (12 % 10) --> 32
number /= 10 --> 1
Third iteration:
total = (total * 10) + (number % 10) = (32 * 10) + (1 % 10) --> 321
number /= 10 --> 0 (Stop the loop)
total = 321
At the end of the function, we just return the value, and make it negative if the original number was negative.
You are not checking if the input was valid. So if we leave that aside and assume the input is a valid integer then you can use a std::string and reverse it via std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::string reverse = input;
std::reverse(reverse.begin(),reverse.end());
if (input == reverse) std::cout << "Palindrome number"
}
I am trying to solve a problem where I have to take the input integers of users until users enter 0, then I have to reverse those words using a function.
I have written a code that works partially but it also gives the output 0 at the end, but the problem doesn't ask for 0 to be printed.
I have tried to fix it, but cannot find a way out.
#include <iostream>
using namespace std;
void reverse(int num) {
int rem = 0;
while (num != 0) {
rem = rem * 10 + num % 10;
num = num / 10;
}
cout << rem << endl;
}
int main() {
int num;
while (num != 0) {
cin >> num;
reverse(num);
if (num == 0)
break;
}
return 0;
}
int main() {
int num = -1;
while (num != 0) {
if (cin >> num) {
if (num == 0) {
break;
}
reverse(num);
}
}
return 0;
}
Hope this will help you and you learn something.
Take input first to avoid garbage values, then proceed to reverse if and only if the number is not equal to zero and a variable with valid type for cin is entered. (i.e. for an integer type variable, cin would expect an integer. Otherwise it will trigger its failbit)
int main()
{
int num;
do { cin>>num;
if(n==0 || !cin) // or !cin.good()
break;
reverse(num);
} while(!num=0)
return 0;
}
Examples:
Input:
314
51
hello
Output:
413
15
Input:
23
0
Output:
32
I am attempting to implement a program that reads a positive integer from the user and outputs all the perfect numbers between 2 and userNum. It also outputs all the pairs of amicable numbers that are between 2 and userNum. Both numbers must be within the range. I am seriously struggling with this.
Requirements:
1) calls to AnalyzeDivisors must be kept to theta(userNum) times all together. 2) Function void AnalyzeDivisors must take the following arguments int num, int& outCountDivs, int& outSumDivs. 3) Function bool IsPerfect must take the following argument int num.
I am honestly at a loss for how to do this within that efficiency range. I currently am able to determine all the perfect numbers in the range by bending the rules as far as parameters to the IsPerfect Function, but how can I determine amicable pairs without calling Analyze Dividors an inordinate amount of times each iteration of the for loop in main?
Any help would be greatly appreciated! Code below:
main
int main()
{
int userNum;
//Request number input from the user
cout << "Please input a positive integer num (>= 2): " << endl;
cin >> userNum;
for (int counter = 2; counter <= userNum; counter++)
{
//Set variables
int outCountDivs = 0, outSumDivs = 0, otherAmicablePair = 0;
bool perfectNum = false, isAmicablePair = false;
//Analyze dividors
AnalyzeDividors(counter, outCountDivs, outSumDivs);
//determine perfect num
perfectNum = IsPerfect(counter, outSumDivs);
if (perfectNum)
cout << endl << counter << IS_PERFECT_NUM;
}
return 0;
}
AnalyzeDividors
void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
{
//both counter and num/divisorCounter
outSumDivs += divisorCounter + (num / divisorCounter);
outCountDivs += 2;
}
else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
{
//Just divisorCounter
outSumDivs += divisorCounter;
outCountDivs += 1;
}
}
}
IsPerfect
bool IsPerfect(int userNum, int outSumDivs)
{
if (userNum == outSumDivs)
return true;
else
return false;
}
I think I found a solution that fits the requirements. I found amicable numbers by storing every number and sum of divisors in a map. If a number's sum of divisors is entered in the map, and the sum of divisor's sum of divisors was the current number, then they are amicable.
Because the results are saved each time, you only call AnalyzeDivisors once per number.
Pardon the lazy variable naming.
#include <iostream>
#include <map>
#include <cmath>
void AnalyzeDivisors(int num, int& divc, int &divs)
{
divc = 1;
divs = 1;
for (int x = 2, y = std::sqrt(num); x <= y; ++x)
{
if (num % x == 0)
{
++divc;
divs += x;
if (num / x != x)
{
++divc;
divs += num / x;
}
}
}
}
bool IsPerfect(int num)
{
static std::map<int, int> amicable;
int divc = 0, divs = 0;
AnalyzeDivisors(num, divc, divs);
if (amicable.find(divs) != amicable.end() && amicable[divs] == num)
std::cout << num << " and " << divs << " are best bros for life.\n";
amicable[num] = divs;
return num == divs;
}
int main()
{
int num;
std::cout << "Pick a number: ";
std::cin >> num;
for (int x = 2; x < num; ++x)
{
if (IsPerfect(x))
std::cout << x << " is perfect in every way!\n";
}
}
This program is for a class. I am required to use two functions. These were the 3 errors listed:
error C2601: 'isPrime' : local function definitions are illegal
error C2601: 'reverse' : local function definitions are illegal
error C1075: end of file found before the left brace '{' at e.
Any other help and tips also greatly appreciate. Thanks!
/*
* 2/07/2013
* Computer Science II
* Homework #1
*/
//Purpose: Display first 'n' (user chosen) number if emirps to the console, five per line.
//Note: An "emirp" is a prime number that is also prime when reversed.
#include <iostream>
using namespace std;
int isPrime(int value); //Prototyle for "prime number function"
int reverse (int value2); //Prototype for "emirp function"
int main()
{
//Ask the user for a positive number
enter code here`enter code here`cout << "Please enter a positive number: ";
int n;
cin >> n;
//Reject negative value input
if ( n < 1)
{
cout << "INVALID NUMBER \n";
}
else
//Calculate all emirps up to 'n'.
for (int test = 0; test < n; test++)
{
int number = 2;
if (isPrime(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
}
}
return 0;
}
int isPrime(int value)
{
//If value is prime, the remainder (count) will be zero twice--for 1 and itself.
int divisor = 1;
int count = 0;
int prime = 0;
if (value % divisor == 0)
{
count++;
++divisor;
}
if (count = 2)
{
int prime = value; //store prime value in new variable
}
return prime;
}
int reverse(int value2)
{
//reverse the number
value2*=10;
value2 = value2 %10;
value2/=10;
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{
{
count2++;
++divisor2;
}
if (count2 = 2)
{
int emirp = value2;
}
}
return emirp;
}
Problem with you syntax in reverse function
:
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{//if
{// ? why this
count2++;
++divisor2;
}//if