I want to find total factors of any number.
In number theory, factorization is the breaking down of a composite number into smaller non-trivial divisors, which when multiplied together equal the original integer. Your job is to calculate number of unique factorization(containing at least two positive integers greater than one) of a number.
For example: 12 has 3 unique factorizations: 2*2*3, 2*6, 3*4 . Note:
3*4 and 4*3 are not considered different.
I have attempted to find that but not getting exact for all.
Here is my code :
#include<iostream>
using namespace std;
int count=0;
void factor(int n,int c,int n1)
{
for(int i=n1; i<n ; i++)
{
if(c*i==n)
{count++;
return;}
else
if(c*i>n)
return;
else
factor(n,c*i,i+1);
}
return;
}
int main()
{
int num,n;
cin>>num;
for(int i=0 ; i<num ; i++)
{
cin>>n;
count=0;
factor(n,1,1);
cout<<count<<endl;
}
return 0;
}
Input is number of test cases followed by test-cases(Numbers).
Example : Input: 3 12 36 3150
Output: 3 8 91
I think you are looking for number of factorizations of a number which are unique.
For this I think you need to find the count of number of prime factor of that number. Say for
12 = 2, 2, 3
Total count = 3;
For 2, 2, 3 we need
(2*2)*3 ~ 4*3
2*(2*3) ~ 2*6
2*2*3 ~ 2*2*3
To solve this we have idea found in Grimaldi, discrete and combinatorial mathematics.
To find number of ways of adding to a number(n) is 2^(n-1) -1. For 3 we have...
3 =
1+1+1
2+1
1+2
Total count = 2^(3-1) -1 = 4-1 = 3
We can use analogy to see that
1+1+1 is equivalent to 2*2*3
1+2 is equivalent to 2*(2*3)
2+1 is equivalent to (2*2)*3
Say number of prime factors = n
So we have number of factorizations = 2^(n-1)-1
The code:
#include <stdio.h>
int power(int x, int y)
{
int prod =1, i ;
for(i=1; i<=y;i++) prod *= x;
return prod;
}
int main()
{
int number,div;
int count = 0, ti, t;
printf("Input: ");
scanf("%d",&t);
for(ti=1; ti<=t;ti++)
{
scanf("%d", &number);
div = 2;count = 0;
while(number != 0)
{
if(number%div!=0) div = div + 1;
else
{
number = number / div;
//printf("%d ",div);
count++;
if(number==1) break;
}
}
printf("%d ", power(2,count-1)-1);
}
return 0;
}
Using mod is really useful in attempting to factor:
for(int i = 1; i <= fnum; ++i){ //where fnum is the number you wish to factor
if(!(fnum % i)) ++count;
}
return count;
Of cross this is the number of factors, not unique factors, if you want the number of unique factors, you have to do some additional work.
The solution is to realize that of all permutations, precisely one is sorted. 2 * 4 * 7 * 3 gives the same result as 2 * 3 * 4 * 7. That means that when you've found one factor, you should not check the remainder for lower factors. However, you should check if the same factor appears again: 12 = 2 * 2 * 3. The sequence 2 2 3 is also sorted.
BTW, you should give your variables clearer names, or at least add some comments describing them.
Related
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.
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{
long long n,k=1,result;
cin >> n;
if(n==1){
result=1;
}else{
for(int i=1,j=1;;i=j,j=j+k){
if(n>i&&n<=j){
result=n-i;
break;
}else{
k++;
}
}
}
cout << result << endl;
}
This is also what I've written before:
#include <iostream>
using namespace std;
int main()
{
long long n,count=0,result;
cin >> n;
for(int i=1;;i++){
for(int j=1;j<=i;j++){
count=count+1;
if(count==n){
result=j;
break;
}
}
if(count>=n){
break;
}
}
cout << result << endl;
}
Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:
1 <= n <= 10^12
So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.
We can group numbers in your sequence:
(1) (1, 2) (1, 2, 3) ...
The overall amount of numbers is
1 + 2 + 3 + ...
The latter is an arithmetic progression, its sum equals to x*(x+1)/2.
We'll find the number of full groups k that go before n+1-th number in the sequence. k equals to the maximal integer such that k*(k+1)/2 <= n. To find it we'll solve the quadratic equation:
x*(x+1)/2 = n
x^2 + x - 2*n = 0
Let's assume that positive root of this equation is x'. We round it down to the nearest integer k. If x' == k (x' is a whole number) it is the answer. Otherwise, the answer is n - k*(k+1)/2.
Exemplary c++ implementation:
double d = 1 + 8.0 * n;
double x = (-1 + sqrt(d)) / 2;
long long k = floor(x);
long long m = k*(k+1) / 2;
if (m == n) {
return k;
} else {
return n - m;
}
The solution has O(1) time complexity.
The first job is to write out the sequence like this:
1
2 3
4 5 6
7 8 9 10
And note that we want to map this to
1
1 2
1 2 3
1 2 3 4
The row position of a number is given by rearranging the formula for an arithmetic progression, solving the resultant quadratic, discarding the negative root, and removing any fractional part of the answer. A number t appears in the row r given by the whole number part
r = R(1/2 + (1/4 + 2 * (t - 1))1/2)
Where R() is a function that rounds a number downwards to the whole number.
But you are after the column c. That is obtained subtracting the value of the first term in that row from t:
c = t - 1/2 * r * (r - 1)
Reference: https://en.wikipedia.org/wiki/Arithmetic_progression
A solution using loop. It will out the number at nth.
x = 0 ;
i = 1 ;
do {
x += i ;
if( x == n ) {
cout<< i ;
break ;
}
else if( x > n ) {
cout<< (n - (x-i)) ;
break ;
}
i ++ ;
}while( 1) ;
I have a problem with one task, so if you could help me a little bit.
Numbers are "lucky" or "unlucky". Number is "lucky" just if every
digit 7
or every digit is 4. So "lucky" numbers are for example 4, 44, 7, 77.
"Unlucky" are the others numbers.
You will get sequence of n-elements and number K. Your task is to
compute number of all possible k-elements subsequence, which fulfill a one
condition. The condition is that in the subsequence mustn't be two same "lucky"
numbers. So for example there mustn't 77 and 77...
Output number of all possible k-elements subsequence mod 10^9+7
0 < N,K < 10^5
Few examples:
Input:
5 2
7 7 3 7 77
Output:
7
Input:
5 3
3 7 77 7 77
Output:
4
Input:
34 17
14 14 14 ... 14 14 14
Output:
333606206
I have code which seems to work, but it is too slow when I try to compute binomial coefficient. I'm using map. In string I store number in string format. In second - int - part of the map is number which represents how many times was that number(in the first map parameter) used. So now I have stored every "unlucky" numbers stored together. Also every same "lucky" number is together. When I have it stored like this, I just compute all multiplications. For example:
Input
5 2
3 7 7 77 7
Are stored like this: map["other"] = 1 map["7"] = 3 map["77"] = 1
Because k = 2 --> result is: 1*3 + 1*1 + 1*3 = 7.
I think problem is with computing binomial coefficient. For the third example it needs to compute (34 choose 17) and it is computing very long time.I've found this article and also this , but I don't understand how they are solving this problem.
My code:
#include<iostream>
#include<string>
#include<map>
#include <algorithm>
#include <vector>
using namespace std;
int binomialCoeff(int n, int k)
{
// Base Cases
if (k == 0 || k == n)
return 1;
// Recur
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}
int main()
{
int n, k;
cin >> n >> k;
map<string, int> mapa; // create map, string is a number, int represents number of used string-stored numbers ---> so if 7 was used two times, in the map it will be stored like this mapa["7"] == 2 and so on)
for (int i = 0; i < n; i++) // I will load number as string, if this number is "lucky" - digist are all 7 or all 4
{ // every "unlucky" numbers are together, as well as all same "lucky" numbers ---> so 77 and 77 will be stored in one element....
string number;
cin >> number;
char digit = number[0];
bool lucky = false;
if (digit == '7' || digit == '4')
lucky = true;
for (int j = 1; j < number.length(); j++) {
if (digit != '7' && digit != '4')
break;
if (number[j] != digit) {
lucky = false;
break;
}
}
if (lucky)
mapa[number]++;
else
mapa["other"]++;
}
vector<bool> v(mapa.size());
bool lack = k > mapa.size(); //lack of elements in map --> it is when mapa.size() < k; i. e. number of elements in array can't make k-element subsequence.
int rest = lack ? k - mapa.size() + 1 : 1; // how many elements from "unlucky" numbers I must choose, so it makes base for binomial coefficient (n choose rest)
if (lack) //if lack is true, different size of vector
fill(v.begin() + mapa.size(), v.end(), true);
else
fill(v.begin() + k, v.end(), true);
int *array = new int[mapa.size()]; //easier to manipulate with array for me
int sum = 0;
int product = 1;
int index = 0;
for (map<string, int> ::iterator pos = mapa.begin(); pos != mapa.end(); ++pos) // create array from map
{
if (lack && pos->first == "other") { //if lack of elements in map, the number in elemets representing "unlucky" numbers will be binomial coefficient (mapa["other] choose rest)
array[index++] = binomialCoeff(mapa["other"], rest);
continue;
}
array[index++] = pos->second;
}
do { // this will create every posible multiplication for k-elements subsequences
product = 1;
for (int i = 0; i < mapa.size(); ++i) {
if (!v[i]) {
product *= array[i];
}
}
sum += product;
} while (next_permutation(v.begin(), v.end()));
if (mapa["other"] >= k && mapa.size() > 1) { // if number of "unlucky" numbers is bigger than k, we need to compute all possible k-elements subsequences just from "unlucky" number, so binomial coefficient (mapa["other] choose k)
sum += binomialCoeff(mapa["other"], k);
}
cout << sum % 1000000007 << endl;
}
Here is my question...
Input a number n from the user. The program should output the sum of all numbers from 1 to n NOT including the multiples of 5.
For example if the user inputs 13 then the program should compute and print the sum of the numbers: 1 2 3 4 6 7 8 9 11 12 13 (note 5,10 are not included in the sum)
i have made the following program but it is not working..
can any one help me THANK YOU in advance...
#include <iostream>
using namespace std;
int main()
{
int inputnumber = 0;
int sum = 0;
int count= 1;
cout<<"Enter the number to print the SUM : ";
cin>>inputnumber;
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
} count = count +1;
cout<<"the sum of the numbers are : "<<sum;
}
You should increment count inside the loop, not outside it:
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
count = count +1; // here
}
Note, by the way, that using a for loop would be much more convenient here. Additionally, sum = sum + count could be shorthanded to sum += count.
for (int count = 1; count <= inputnumber; ++count)
{
if (count % 5 != 0)
{
sum += count;
}
}
You need to put the count+1 inside your while loop. also add !=0 tou your if statement.
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
count = count +1;
}
No need to use a loop at all:
The sum 1..n is
n * (n+1) / 2;
the sum of the multiples of 5 not above n is
5 * m * (m+1) / 2
where m = n/5 (integer devision). The result is therefore
n * (n+1) / 2 - 5 * m * (m+1) / 2
Try this..
In my condition,checks n value is not equal to zero and % logic
int sum = 0;
int n = 16;
for(int i=0 ; i < n ;i++) {
if( i%5 != 0){
sum += i;
}
}
System.out.println(sum);
Let's apply some maths. We'll use a formula that allows us to sum an arithmetic progression. This will make the program way more efficient with bigger numbers.
sum = n(a1+an)/2
Where sum is the result, n is the inpnum, a1 is the first number of the progression and an is the place that ocuppies n (the inpnum) in the progression.
So what I have done is calculate the sum of all the numbers from 1 to inpnum and then substract the sum of all the multiples of 5 from 5 to n.
#include <iostream>
using namespace std;
int main (void)
{
int inpnum, quotient, sum;
cout << "Enter the number to print the SUM : ";
cin >> inpnum;
// Finds the amount of multiples of 5 from 5 to n
quotient = inpnum/5;
// Sum from 1 to n // Sum from 5 to n of multiples of 5
sum = (inpnum*(1+inpnum))/2 - (quotient*(5+(quotient)*5))/2;
cout << "The sum of the numbers is: " << sum;
}
thanks every one but the problem is solved . the mistake was very small. i forget to write "()" in if condition.
#include <iostream>
using namespace std;
int main()
{
int inputnumber = 0;
int sum = 0;
int count= 1;
cout<<"Enter the number to print the SUM : ";
cin>>inputnumber;
while(count<=inputnumber)
{
if ((count % 5)!=0)//here the ()..
{
sum = sum + count;
}
count = count +1;
}
cout<<"the sum of the numbers are : "<<sum;
}
100 - The 3n + 1 problem
http://www.spoj.com/problems/PROBTRES/
always i get this >>> runtime error (SIGSEGV) <<<
why plz help !
Background:
Problems in Computer Science are often classified as belonging to a certain class of problems (e.g., NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs.
The Problem:
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n = 3n + 1
5. else n = n / 2
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
The Input:
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output:
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
Sample Input:
1 10
100 200
201 210
900 1000
Sample Output:
1 10 20
100 200 125
201 210 89
900 1000 174
#include <iostream>
using namespace std ;
long int a[1000001];
long int F (long int n){
if(a[n]!=0)
return a[n];
else {
if(n%2 !=0)
a[n]=F(n*3+1)+1 ;
else
a[n]=F(n/2)+1 ;
return a[n];
}
}
int main(){
a[1]= 1 ;
long int i , j , MX , MN , x=0 ;
while (cin>>i >> j ){
MX=max(i,j);
MN=min(i,j);
for(;MN<=MX;MN++){
if(x<F(MN))
x=F(MN) ;
}
cout<<i<<" "<<j<<" "<<x<<endl;
x= 0;
}
return 0 ;
}
what is the difference between this and my code ?!!!
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000001
static int result[MAX];
int calculate(unsigned long i);
int main()
{
unsigned long int i = 0;
unsigned long int j = 0;
unsigned long int k = 0;
int max,x,y;
result[1] = result[0] = 1;
while (scanf("%ld",&i)!= EOF)
{
scanf("%ld",&j);
if (i > j)
{
x = i;
y = j;
}
else
{
x = j;
y = i;
}
max = 0;
for (k = y; k <= x; k++)
{
if (result[k] != 0 && result[k] > max)
max = result[k];
else if (calculate(k) > max)
max = result[k];
}
printf("%ld %\ld %d\n",i,j,max);
}
return 0;
}
int calculate(unsigned long i)
{
if (i < MAX && result[i])
return result[i];
if ( i % 2 == 1 )
{
if (i < MAX)
return result[i] = 2+calculate((3*i+1)/2);
else
return 2+calculate((3*i+1)/2);
}
else
{
if( i < MAX)
return result[i] = 1 + calculate(i / 2);
else
return 1 + calculate(i /2 );
}
}
You might check the actual range of values you're getting for n, as it might be stepping outside your array long a[1000001]. Also, you might check your recursion depth. If you recurse too deeply, you'll overflow the stack.
I would consider adding an assert to test n (ie. assert(n < 1000001)), and perhaps a recursion depth variable to check your recursion depth as the first steps to diagnosing and debugging this code. You can find assert in <cassert>.