public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int sum=0;
for(int i=1;i<=a;i++){
System.out.print("Next integer?");
int v=console.nextInt();
if(i%2==0){
sum=sum+v;
}else{
}
}
System.out.println("Sum of even is "+sum);
}
and How i can find maximum even number in for loop?
i need to write System.out.print("maximum even is "+????);
You can try with following code:
public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int maxEven = 0;
for(int i=1;i<=a;i++){
System.out.print("Next integer?");
int v=console.nextInt();
if(v%2==0){
if(v > maxEven)
maxEven = v;
}
}
System.out.println("Maximum even is " + maxEven);
}
You can use this: (added to your existing code)
public static void evenSumMax(Scanner console) {
System.out.print("How many integers?");
int a = console.nextInt();
int sum = 0;
int max = Integer.MIN_VALUE; // the smallest value possible in 32-bit integer
for (int i = 1; i <= a; i++) {
System.out.print("Next integer?");
int v = console.nextInt();
// assuming you're looking for max odd number in input numbers
if (v % 2 == 0 && v > max) {
max = v;
}
if (i % 2 == 0) {
sum = sum + v;
} else {}
}
System.out.println("Sum of even is " + sum);
System.out.print("maximum even is "+ max);
}
The following will work. After checking the condition that entered value is even add it to the sum variable and compare it to the maxInt. If the entered number is larger than the previously entered number then set maxInt to new value.
public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int sum=0;
int maxInt=0;
for(int i=0;i<a;i++)
{
System.out.print("Next integer?");
int v=console.nextInt();
if(v%2==0){
sum=sum+v;
if(maxInt<v){
maxInt=v;
}
}
}
System.out.println("Sum of even is "+sum);
System.out.println("Maximum even number is "+maxInt);
}
Related
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with.
In my implementation fun1 works as expected and returns the max remainder, fun2 is supposed to give 3 but its giving 2 .probably mistake is at break statement.
Sample input: 5
Expected output: 2 3.
My output: 2 2.
#include <iostream>
#include <algorithm>
using namespace std;
int fun2(int a);
int fun1(int n ,int num);
int main(){
int n = 0; int num = 0;;
cin >> n;
int p = fun1(n, num);
cout << p << "\n";
cout << fun2(p);
}
int fun1(int n, int num){
int b = 0;
for(int i = 1; i <= n; i++){
num = n % i;
b = max(num, b);
}
return b;
}
int fun2(int n,int p ){
int num = 0; int c = 0; int d = 0;
for(int i = 1; i <= n; i++){
num = n % i;
c = max(num, c);
if(c == p){
break;
}
d = i;
}
return d;
}
Since you already managed to successfully find the biggest remainder, you may get use of this function and return the number this remainder is found with:
std::pair<int, int> biggestRemDem(int value) {
int dm = 1;
int rm = 0;
for(int i = dm; i <= value; ++i){
const auto tmpRm = value % i;
if (tmpRm > rm) {
rm = tmpRm;
dm = i;
}
}
return { rm, dm };
}
The signature of the function needs to return std::pair however, but you no longer need the std::max, so the headers required to include are also changed:
#include <iostream>
#include <utility>
std::pair<int, int> biggestRemDem(int value);
int main(){
int n{};
std::cin >> n;
const auto result = biggestRemDem(n);
std::cout << result.first << " " << result.second << std::endl;
}
In fun2 you have:
if(c == p){
break;
}
d = i;
When you found the right index so that c == p the break will exit the loop and d == i; is not execute. Therefore d has the value from the previous loop, i.e. one less than you need.
Apart from that the code really smells:
fun1
should not have a second argument sum.
should remember the index where if found the largest remainder and you would be done
fun2
the maximum remainder is p, no need to max(num, c). Actually drop the c alltogether and just use num == p
n % 1 == 0 and n % n == 0. The loop will always break with i < n. Might as well not have a conditional: for(int i = 1; ; i++)
you need d because at the end of the loop i disappears. Why not pull i out of the loop? int i; for(i = 1; ; i++)
and now you can use a different conditional again
int fun2(int n,int p ){
int i;
for(i = 1; n % i != p; i++) { }
return i;
}
or
int fun2(int n,int p ){
int i = 1;
for(; n % i != p; i++) { }
return i;
}
or
int fun2(int n,int p ){
int i = 1;
while(n % i != p) ++i;
return i;
}
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with.
It seems that the asker decided to solve this in two steps. They wrote a function fun1 returning the maximum remainder and a function fun2, which fed with the previously calculated remainder, returns the corresponding dividend.
While not an efficient approach, it could work if implemented correctly, but that's not the case.
Other than some (very) bad naming choices, we can find:
In the original version of the posted code, fun2 has a function prototype with a single parameter and it is called passing the value returned by fun1, which is the maximum remainder. The problem is that this way the function has no way to know what was the original value of n and actually declares a local n, initialized to zero, so that the body of the loop for(int i = 1; i <= n; i++) is never executed.
The actual version of this question shows a definition of fun2 with two parameters, that can't compile unless both the prototype and the call site are changed accordingly.
Assuming that the original n and the remainder p were succesfully passed to fun2, there still would be another issue:
int fun2(int n, int p ) {
int c = 0, d = 0;
for(int i = 1; i <= n; i++) {
int num = n % i;
c = max(num, c);
if(c == p){ // So, if we reach the passed remainder...
break; // We break out of the loop, skipping...
}
d = i; // this line, meaning...
}
return d; // That the dividend previous to the correct one is returned!
}
They could just return i; when c == p.
The answer by The Dreams Wind presents a much better approach to this task. I'd like to suggest an O(1) solution, though. Consider these points:
The result of n % i can't be equal or greater than i. It's in the range [0, i).
n / 2 is the greatest number that can divide n other than n itself. It means that all the numbers i in (n/2, n) are such that n % i > 0.
For every number i in (n/2, n), we can actually say that n % i = n - i.
So, when n is greater than 2, the i corresponding to the maximum remainder is just 1 + n/2 and said remainder is n - n/2 - 1.
I'm trying to write a c++ program which gets an integer n (n>=1 && n<=100000) from the user and puts the sum of its digits into b. The output needed is the b-th prime number coming after n. I'm an absolute beginner in programming so I don't know what's wrong with the for loop or any other code that it doesn't show the correct output. For example the 3rd prime number after 12 (1+2=3) is 19 but the loop counts the prime numbers from 2 instead of 12, so it prints 7 as result.
#include <iostream>
using namespace std;
bool isPrime(int n)
{
if(n <= 1)
return false;
for(int i = 2; i <= (n/2); i++)
if(n % i == 0)
return false;
return true;
}
int main()
{
long int n;
int b = 0;
cin>>n;
while(n >= 1 && n <= 100000){
b += n % 10;
n /= 10;
}
for(int i = n, counter = b; counter <= 10; i++)
if(isPrime(i)){
counter++;
if(i > n)
cout<<counter<<"th prime number after n is : "<<i<<endl;
}
return 0;
}
So one of the possible solutions to my question, according to #Bob__ answer (and converting it to the code style I've used in the initial code) is as follows:
#include <iostream>
using namespace std;
bool isPrime(long int number)
{
if(number <= 1)
return false;
for(int i = 2; i <= (number / 2); i++)
if(number % i == 0)
return false;
return true;
}
int sumOfDigits(long int number)
{
int sum = 0;
while(number >= 1 && number <= 100000)
{
sum += number % 10;
number /= 10;
}
return sum;
}
long int bthPrimeAfter(int counter, long int number)
{
while(counter)
{
++number;
if(isPrime(number))
--counter;
}
return number;
}
int main()
{
long int number;
cin>>number;
int const counter = sumOfDigits(number);
cout<<bthPrimeAfter(counter, number)<<"\n";
return 0;
}
As dratenik said in their comment:
You have destroyed the value in n to produce b in the while loop. When the for loop comes around, n keeps being zero.
That's a key point to understand, sometimes we need to make a copy of a variable. One way to do that is passing it to a function by value. The function argument will be a local copy which can be changed without affecting the original one.
As an example, the main function could be written like the following:
#include <iostream>
bool is_prime(long int number);
// ^^^^^^^^ So is `n` in the OP's `main`
int sum_of_digits(long int number);
// ^^^^^^^^^^^^^^^ This is a local copy.
long int nth_prime_after(int counter, long int number);
int main()
{
long int number;
// The input validation (check if it's a number and if it's in the valid range,
// deal with errors) is left to the reader as an exercise.
std::cin >> number;
int const counter = sum_of_digits(number);
std::cout << nth_prime_after(counter, number) << '\n';
return 0;
}
The definition of sum_of_digits is straightforward.
int sum_of_digits(long int number)
{
int sum = 0;
while ( number ) // Stops when number is zero. The condition n <= 100000
{ // belongs to input validation, like n >= 0.
sum += number % 10;
number /= 10; // <- This changes only the local copy.
}
return sum;
}
About the last part (finding the nth prime after the chosen number), I'm not sure to understand what the asker is trying to do, but even if n had the correct value, for(int i = n, counter = b; counter <= 10; i++) would be just wrong. For starters, there's no reason for the condition count <= 10 or at least none that I can think of.
I'd write something like this:
long int nth_prime_after(int counter, long int number)
{
while ( counter )
{
++number;
if ( is_prime(number) )
{
--counter; // The primes aren't printed here, not even the nth.
}
}
return number; // Just return it, the printing is another function's
} // responsabilty.
A lot more could be said about the is_prime function and the overall (lack of) efficiency of this algorithm, but IMHO, it's beyond the scope of this answer.
So I created a c++ code that counts "special" numbers in a given range, which is defined as a number where the total of its number of 1-bits in its binary representation is less than our equal to 3 (i.e. 1(1), 2(10), 3(11), 4(100), 5(101), 6(110), 7(111), 8(1000).
I successfully created the code, however there is one problem. At high number ranges, it outputs segmentation fault.
Any idea as to why this happens?
#include <iostream>
#include <cmath>
using namespace std;
long special(long x, long y){
long sArray[y];
long output = 0;
sArray[0]=0;
sArray[1]=1;
for(long i = 2; i<=y; i++){
long j = floor(i/2);
sArray[i] = sArray[j]+(i%2);
if (i>=x && sArray[i]<=3){
output++;
}
}
return output;
}
int main()
{
cout<<special(5,2717261);
return 0;
}
The segmentation fault occurs because you try to declare an array that's too large and extends outside the current memory segment.
Frankly, you don't need this array, and can just count the number of special numbers in the given range:
boolean isSpecial(long num) {
int bits = 0;
while (num > 0) {
if (num % 2 > 0) {
++bits;
if (bits >= 3) {
return true;
}
}
num /= 2;
}
return false;
}
long special(long x, long y) {
long output = 0;
for(long i = x; i <= y; ++i) {
if (isSpecial(i)) {
++output;
}
}
return output;
}
A number is said to have n prime divisors if it can factored into n prime numbers (not necessarily distinct).
E.g.:
12 = 2*2*3 ---> 12 has 3 prime divisors
Given numbers a and b we have to find the number of such prime divisors of a!/b!(a>=b). Hence I decided to do the following way:
long long pre[5000001];
long long solve(int num)
{
if(!num)
return 0;
if(pre[num] || num==1)
return pre[num];
int num1=num;
if(num1%2==0)
{
int cnt=0;
while(num1%2==0)
{
num1/=2;
cnt++;
}
pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
return pre[num];
}
for(int i=3;i<=(int)(sqrt(num1))+1;++i)
{
if(num1%i==0)
{
int cnt=0;
while(num1%i==0)
{
cnt++;
num1/=i;
}
pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
return pre[num];
}
}
if(num>1)
{
pre[num]=1 + solve(num-1);
return pre[num];
}
}
int main()
{
int t;
cin>>t;
pre[1]=0;
while(t--)
{
int a,b;
cin>>a>>b;
long long ans = solve(a)-solve(b);
cout<<ans<<endl;
}
return 0;
}
My approach was to basically to calculate the number of prime divisors and store them because the limit for a and b was <=5000000. pre[num] gives the sum of number of prime divisors of all numbers <=num. But it results in run-time error for larger inputs such as a=5000000 b=4999995. Is there any better way to do this or the present approach can be tweaked for a better solution?
You reach your limit of recursion.
To fix your problem, your may build your array from 0 to a first:
int main()
{
int max_a = 0;
int t;
cin >> t;
pre[1] = 0;
while(t--)
{
int a, b;
cin >> a >> b;
for (int i = max_a; i < a; ++i) {
solve(i); // memoization until `a` max recursion is limited to 1 :)
}
max_a = std::max(max_a, a);
long long ans = solve(a) - solve(b);
std::cout << ans << std::endl;
}
}
So I am a beginner in c++ programming and I was doing some problem online.
I have to calculate all the products of numbers from 999 to 100 (Eg.999*999 , 999*998 ... 800* 800 , 800 *799 ... , 100 * 100). I can easily print out these products but when I try to pass these values to a function they do not work.
Can you please look at the following code and point out anything that's wrong?
I think its got something to do with buffer but I have no idea how to fix that. Thanks.
#include <iostream>
using namespace std;
unsigned long int num,rev,temp,rem = 0,reversed = 0;
int ispalin(unsigned long int n)
{
temp=n;
while(temp!=0)
{
rem = temp%10;
reversed = reversed*10 + rem;
temp/=10;
}
if(reversed == n)
{
return 1;
}
return 0;
}
int main()
{
int maxi = 0;
for (int i =999 ; i >= 100;i--)
{
for(int j = i;j >= 100; j--)
{
rev = ispalin(i*j);
if (rev == 1)
{
if(i*j > maxi)
{
maxi = i*j;
}
}
}
}
cout<<maxi<<" This is max"<<endl;
}
reversed must be reset to zero at the beginning of every check for palindrome. The best would be to make reversed (and others) a local variable of ispalin.