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;
}
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.
I've been trying to submit this to a website with programming lessons, but the judge keeps telling me that this program takes too long to execute :/
Problem Statement:
Write a program that reads a non-negative integer n from the standard input, will count the digit of tens and the digit of ones in the decimal notation of n!, and will write the result to the standard output. In the first line of input there is one integer D (1≤D≤30), denoting the number of cases to be considered. For each case of entry. your program should print exactly two digits on a separate line (separated by a single space): the tens digit and the ones digit of n! in the decimal system.
Input/Output:
Input
Output
2
1
0 1
4
2 4
#include <iostream>
using namespace std;
int d,n;
int main()
{
cin>>d;
for(int i=0; i<d; i++)
{
cin>>n;
int silnia = 1;
for(int j=n; j>1; j--)
{
silnia=silnia*j;
}
if(silnia == 1) cout<<0<<" "<<silnia<<"\n";
else cout<<(silnia/10)%10<<" "<<silnia%10<<"\n";
}
return 0;
}
You can get rid of inner loop since n! == (n - 1)! * n:
cin >> d;
int factorial = 1;
cout << 0 << " " << 1 << "\n";
for (int i = 1; i < d; ++i) {
/* we operate with last two disgits: % 100 */
factorial = (factorial * i) % 100;
cout << factorial / 10 << " " << factorial % 10 << "\n";
}
Edit: Another issue is with
silnia=silnia*j;
line. Factorial grows fast:
13! = 6227020800 > LONG_MAX (2147483647)
that's why we should use modulo arithmetics: we keep not factorial itself (which can be very large), but its two last digits (note % 100), which is garanteed to be in 00..99 range:
factorial = (factorial * i) % 100;
Or even (if i can be large)
factorial = (factorial * (i % 100)) % 100;
Since only the last 2 digits of n! are needed, any n >= 10** will have a n! with 00 as the last 2 digits.
A short-cut is to test n: This takes the problem from O(n) to O(1).
int factorial = 0;
if (n < 10) {
int factorial = 1;
for(int j=n; j>1; j--)
{
factorial *= j;
}
factorial %= 100;
}
Or use a look-up table for n in the [0...10) range to drop the for loop.
---
** 10_or_more! has a 2 * 5 * 10 * other factors in it. All these factorials then end with 00.
Given a natural number n (1 <= n <= 500000), please output the summation of all its proper divisors.
Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.
e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.
<<--This is a challenge i am trying to do and i am using recursion
int find_sum(std::vector <int> nums,long int sum,int num_now,long int j)
{
if(j<nums[num_now])
{
if(nums[num_now]%j==0)
{
sum=sum+j;
}
return find_sum(nums,sum,num_now,j+1);
}
else
{
return sum;
}
}
sum is the sum of all divisors,nums is the vector i stored number in,num_now is current member in vector,int j is 1 i use it to search for dividers,sadly using this i cant use numbers like 500000 it give's me error,is there any better way to do it or have i made a mistake somewhere.
--Thank you for your time
Here is a recursive way to solve your problem:
int find_sum(int x, int i)
{
if(i == 0)
return 0;
if(x % i == 0)
return i + find_sum(x, (i-1));
return find_sum(x, (i-1));
}
You need to call find_sum(N, N-1); in order to find sum of dividers of N (i must be less than given N because of strict inequality).
In your case it would be find_sum(20, 19);
e.g. my function returns:
71086 for N = 50000
22 for N = 20
0 for N = 1
I don't see the reason why you need to use recursion for solving this problem. I would prefer a more staightforward way to solve it.
long CalculateSumOfDivisors(int number)
{
long sum = 0;
for(int i=1; i<number; i++)
{
// If the remainder of num/i is zero
// then i divides num. So we add it to the
// current sum.
if(number%i==0)
{
sum+=i;
}
}
return sum;
}
Furthermore, we could write a more optimal algorithm, if we note the following:
Let that we have a number n and d is the smallest divisor of n that is greater of 1. (Apparently if the number n is a prime number there is any such a divisor). Then the larget divisor of n is the number n/d.
Based on this we can formulate a more optimal algorithm.
long CalculateSumOfDivisors(int number)
{
int smallestDivisor = FindSmallestDivisor(number);
if(smallestDivisor==1) return 1;
long sum = smallestDivisor;
// Calculate the possible greatest divisor.
int possibleGreatestDivisor = (int)floor(number/smallestDivisor);
for(int i=smallestDivisor+1; i<=possibleGreatestDivisor; i++)
{
if(number%i==0)
{
sum+=i;
}
}
return sum;
}
int FindSmallestDivisor(int number)
{
int smallestDivisor = 1;
for(int i=2; i<number; i++)
{
if(number%i==0)
{
smallestDivisor = i;
break;
}
}
return smallestDivisor;
}
I tried writing code with main function asking user to give the it wants to get sum of. here is the code , hope it helps.
#include<iostream>
using namespace std;
int Sum(int min, int max, int &val, int &sum){
if(min >= max)
return 0;
for ( ; min < max; min++){
if ( val%min == 0){
sum += min + val/min;
return Sum(++min,val/min, val,sum);
}
}
return 0;
}
int main(){
int s=1;
int val;
cout <<"Enter Val to sum:";
cin >> val;
Sum(2,val,val,s);
cout <<"Sum is :"<<s<<endl;
return 0;
}
Here Sum function is used recursively and passed parameters as shown in the code.
Hope it helps.
I don't think you should use recursion.
Instead start by looping from 1..N-1
When you find a divisor adjust the end value for the loop. Example if 2 is a divisor then you know N/2 is also a divisor. And just as important you know there can be no further divisors in the range ]N/2:N[. Likewise if 3 is a divisor then you know N/3 is also a divisor and you know there are no more divisors in the range ]N/3:N[.
Following that concept you can reduced the number of loops significantly for most numbers.
Something like:
long find_sum(int num)
{
long sum = 0;
int max = num;
int i = 1;
while(i < max)
{
if(num % i == 0)
{
sum += i; // Add i to the sum
max = num / i; // Decrement max for performance
if (max != i && max != num)
{
sum += max; // Add max when max isn't equal i
}
}
i++;
}
return sum;
}
Example:
num = 10
sum = 0
i = 1 -> sum = 1, max = 10
i = 2 -> sum = 1+2+5, max = 5
i = 3 -> sum = 1+2+5, max = 5
i = 4 -> sum = 1+2+5, max = 5
i = 5 -> return 8 (1+2+5)
num = 64
sum = 0
i = 1 -> sum = 1, max = 64
i = 2 -> sum = 1+2+32, max = 32
i = 3 -> sum = 1+2+32, max = 32
i = 4 -> sum = 1+2+32+4+16, max = 16
i = 5 -> sum = 1+2+32+4+16, max = 16
i = 6 -> sum = 1+2+32+4+16, max = 16
i = 7 -> sum = 1+2+32+4+16, max = 16
i = 8 -> sum = 1+2+32+4+16+8, max = 8
i = 9 -> return (1+2+32+4+16+8)
The number of loops are kept down by changing max whenever a new divisor is found.
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.
Here's the problem.
Write the given number N, as sum of the given numbers, using only additioning and subtracting.
Here's an example:
N = 20
Integers = 8, 15, 2, 9, 10
20 = 8 + 15 - 2 + 9 - 10.
Here's my idea;
First idea was to use brute force, alternating plus and minus. First I calculate the number of combinations and its 2^k (where k is the nubmer of integers), because I can alternate only minus and plus. Then I run through all numbers from 1 to 2^k and I convert it to binary form. And for any 1 I use plus and for any 0 I use minus. You'll get it easier with an example (using the above example).
The number of combinations is: 2^k = 2^5 = 32.
Now I run through all numbers from 1 to 32.
So i get: 1=00001, that means: -8-15-2-9+10 = -24 This is false so I go on.
2 = 00010, which means: -8-15-2+9-10 = -26. Also false.
This method works good, but when the number of integers is too big it takes too long.
Here's my code in C++:
#include <iostream>
#include <cmath>
using namespace std;
int convertToBinary(int number) {
int remainder;
int binNumber = 0;
int i = 1;
while(number!=0)
{
remainder=number%2;
binNumber=binNumber + (i*remainder);
number=number/2;
i=i*10;
}
return binNumber;
}
int main()
{
int N, numberOfIntegers, Combinations, Binary, Remainder, Sum;
cin >> N >> numberOfIntegers;
int Integers[numberOfIntegers];
for(int i = 0; i<numberOfIntegers; i++)
{
cin >>Integers[i];
}
Combinations = pow(2.00, numberOfIntegers);
for(int i = Combinations-1; i>=Combinations/2; i--) // I use half of the combinations, because 10100 will compute the same sum as 01011, but in with opposite sign.
{
Sum = 0;
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Remainder==1)
{
Sum += Integers[numberOfIntegers-1-j];
}
else
{
Sum -= Integers[numberOfIntegers-1-j];
}
}
if(N == abs(Sum))
{
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Sum>0)
{
if(Remainder==1)
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
}
else
{
if(Remainder==1)
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
}
}
break;
}
}
return 0;
}
Since this is typical homework, I'm not going to give the complete answer. But consider this:
K = +a[1] - a[2] - a[3] + a[4]
can be rewritten as
a[0] = K
a[0] + a[2] + a[3] = a[1] + a[4]
You now have normal subset sums on both sides.
So what you are worried about is you complexity .
Lets analyse what optimisations can be done.
Given n numbers in a[n] and target Value T;
And it is sure one combination of adding and subtracting gives you T ;
So Sigma(m*a[k]) =T where( m =(-1 or 1) and 0 >= k >= n-1 )
This just means ..
It can written as
(sum of Some numbers in array) = (Sum of remaining numbers in array) + T
Like in your case..
8+15-2+9-10=20 can be written as
8+15+9= 20+10+2
So Sum of all numbers including target = 64 // we can cal that .. :)
So half of it is 32 as
Which if further written as 20+(somthing)=32
which is 12 (2+10) in this case.
Your problem can be reduced to Finding the numbers in an array whose sum is 12 in this case
So your problem now can be reduced as find the combination of numbers whose sum is k (which you can calculate as described above k=12 .) For Which the complexity is O(log (n )) n as size of array , Keep in mind that you have to sort array and use binary search based algo for getting O(log(n)).
So as complexity can be made from O(2^n) to O((N+1)logN)as sorting included.
This takes static input as you have provided and i have written using core java
public static void main(String[] args) {
System.out.println("Enter number");
Scanner sc = new Scanner(System.in);
int total = 0;
while (sc.hasNext()) {
int[] array = new int[5] ;
for(int m=0;m<array.length;m++){
array[m] = sc.nextInt();
}
int res =array[0];
for(int i=0;i<array.length-1;i++){
if((array[i]%2)==1){
res = res - array[i+1];
}
else{
res =res+array[i+1];
}
}
System.out.println(res);
}
}