C++ Program to print sum of digits - c++

//Program to print sum of digits
#include <iostream>
using namespace std;
int main()
{
int n, m, sum = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
m = n % 10;
sum += m;
n = n / 10;
}
cout << sum;
}
//Outputs
// Input = 123
// Output = 5 (should be 6)
// Input = 0235
// Ouput = 8 (should be 9)
Not printing the right answer when input no. is starting from 1 or 0.
By using While (n>0), it's giving the right output but I can't figure out why?

For starters the user can enter a negative number because the type of the variable n is the signed type int.
Thus neither loop either
for(int i = 0; i < n; i++)
or
while (n>0)
will be correct.
A correct loop can look like
while ( n != 0 )
And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.
As for this loop
for(int i = 0; i < n; i++)
then it entirely does not make a sense.
For example let's assume that n is initially equal to 123,
In this case the in the first iteration of the loop the condition of the loop will look like
0 < 123
In the second iteration of the loop it will look like
1 < 12
And in the third iteration of the loop it will look like
2 < 1
That means that the third iteration of the loop will not be executed.
Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.

Related

how to fix this programme

Given an array A, find the highest unique element in array A. Unique element means that element should present only once in the array.
Input:
First line of input contains N, size of array A. Next line contains N
space separated elements of array A.
Output:
Print highest unique number of array A. If there is no any such
element present in array then print -1.
Constraints:
1 ≤ N ≤ 106 0 ≤ Ai ≤ 109
SAMPLE INPUT
5 9 8 8 9 5
SAMPLE OUTPUT
5
Explanation
In array A: 9 occur two times. 8 occur two times. 5 occur once hence the answer is 5.
Can you explain what is wrong with this code?
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[n], i, max = -99;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
cout << max;
}
}
for (i = 0; i < n; i++) {
if (max == a[i]) {
break;
} else {
// cout<<"-1";
}
max =
}
return 0;
}
There's a few problems here (right now it won't even compile at max =). But the algorithmic problem is this: the second for loop finds the maximum before rejecting duplicate entries. The reverse is needed. First reject duplicates (say, by setting them to -99), then find the max of what is left over.

C++ Largest number in array. Positive and negative

I have a task to print maximum int of matrix second line.
Example input:
3 2 (n, m)
-1 -2 <- 1 line
4 5 <- 2 line
2 6 <- 3 line
Max int in second line is 5. My program prints it. But if second line would be -100 -150, it not works. Sure it is because I have max = 0, but I don't know how to use it properly. I'm a student. Thanks in advance.
It is my code:
#include <iostream>
using namespace std;
int main() {
int n, m, max = 0;
cin >> n >> m;
int matrix[10][10];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[1][j] > max) {
max = matrix[1][j];
}
}
}
if (max == 0 || n == 1) {
cout << "No";
} else {
cout << max;
}
}
And code works pretty good, unless there are negative numbers in second line
You are correct to suspect max = 0;. Why is that a problem? Well, first, perhaps you should try to explain to your rubber duck why it is correct. As you try to do so, you are likely to express an intent along the lines of "this value will not make it through the checks" or "this value will be replaced in the first iteration of the loop". Why? "Because matrix[1][j] > max will be true, so... Hold on, wasn't the problem when matrix[1][j] > 0 is false? So when max is 0, um... problem?"
The overall strategy is valid, but there is a requirement that max be initialized to a low enough value. There are two common strategies I can think of at the moment.
Use a value that is as low as possible for the type you are using. That is:
int max = std::numeric_limits<int>::lowest();
Use the value from the first iteration of the loop. No need to provide a value that is just going to be replaced anyway. There are some caveats for this, though. The most relevant for your example can be expressed as a question: what if there is no first iteration? (Perhaps there is only one row? Perhaps there are no columns?) Also, you would need to initialize max between your loops, after the matrix has been given values.
int max = (n > 1 && m > 0) ? matrix[1][0] : /* what value do you want here? */;

(C++) Finding all prime numbers between two integers (without using sieve of Eratosthanes)

I'm trying to find all the prime numbers between two integers and place them in an integer array.
The catch is that i have to use a specific method of doing so (divide each subsequent integer by all the primes in my array). So I can't use the sieve of Eratosthanes or any other 'easier' methods.
My code successfully prompts the user for two integers, but for now I do not use either of them. First I want to make sure the program works for values between 0 and whatever, in this case 200 just to test it.
Problem is, when I run the program and print the first 20 or so values in the array, I'm getting
2, 3, 5, 7, 11, 200, 0, 0, 0, 0, 0, 0 ...... more zeroes.
The first 5 values are correct because they start in the array, but after that the whole thing goes haywire.
I've worked through my nested loop by hand for a couple values and it SEEMS like it should work. I feel like there's a specific array property that I'm overlooking.
Here's my code:
#include "stdafx.h"
#include "iostream"
#include "climits"
#include "cmath"
#include "array"
using namespace std;
int main()
{
// declare variables to store user input
int lowerBound, upperBound;
// prompt user for lesser and greater integers and store them
cout << "Program to find all primes between two integers." << endl;
cout << "Enter lesser integer: " << endl;
cin >> lowerBound;
cout << "Enter greater integer: " << endl;
cin >> upperBound;
// if statement to switch the input variables if the user accidentally enters them backwards
if (lowerBound > upperBound) {
int temp = lowerBound;
lowerBound = upperBound;
upperBound = temp;
}
// initialize int array with the first 5 primes
int primes[100] = { 2, 3, 5, 7, 11 };
// loop to find primes between 12 and 200 (since we already have primes from 1-11 in the array)
for (int i = 12; i <= 200; i++) {
// the maximum divisor needed to determine if the current integer being tested is prime
double maxDivisor = sqrt(i);
// variable for the current size of the array
int size = 5;
// boolean variable is set to true by default
bool isPrime = true;
for (int j = 0; j < size; j++) { // changed "j<=size" to "j<size"
int remainder = (i % primes[j]);
// once the maximum divisor is reached, there is no need to continue testing for the current integer
if (primes[j] > maxDivisor) {
break;
}
// if the remainder of divison by a prime is 0, the number is not prime, so set the boolean variable to false
if (remainder = 0) {
isPrime = false;
}
}
// if isPrime is still true after the nested loop, the integer value being tested will be placed in the next element of the array
if (isPrime == true) {
primes[size] = i;
// since we added to the array, increment size by 1
size++;
}
}
// display the first 20 values in the array for debugging
for (int k = 0; k < 20; k++) {
cout << primes[k] << ", ";
}
system("pause");
return 0;
}
This here
if (remainder = 0) {
isPrime = false;
}
Needs to be changed to
if (remainder == 0) {
isPrime = false;
}
Because = does assignment, not comparison. So what remainder = 0 does it setting remainder to 0, and then it returns that 0, which gets casted to false, which is on of the reasons why it's not finding any primes.
Also, as Fantastic Mr Fox pointed out, for (int j = 0; j <= size; j++) needs to be changed to for (int j = 0; j < size; j++).
Also, did your compiler issue any warnings? If not, try to see if you can set it to be more strict with warnings. I figure most modern compilers will give you a hint at if (remainder = 0). Getting useful warnings from the compiler helps a lot with preventing bugs.
Edit:
As Karsten Koop pointed out, you need to move the int size = 5; out of the loop, to before the for (int i = 12;. With those changes, it's now working on my machine.
Last but not least, a tip: instead of if (isPrime == true), you can just write if (isPrime).

c++:Hackerank:Error in taking input

This is a part of my question.I tried many times but couldn't get the answer
Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams.
Input Format
The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow.
Each line contains a binary string of length M. If the ith line's jth character is 1, then the ith person knows the jth topic; otherwise, he doesn't know the topic.
Constraints
2≤N≤500
1≤M≤500
Output Format
On the first line, print the maximum number of topics a 2-person team can know.
On the second line, print the number of 2-person teams that can know the maximum number of topics.
Sample Input
4 5
10101
11100
11010
00101
Sample Output
5
2
Explanation
(1, 3) and (3, 4) know all the 5 topics. So the maximal topics a 2-person team knows is 5, and only 2 teams can achieve this.
this is a a part of my work.Any clue how can i get this to work
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, m, max = 0, max1 = 0, count = 0;
cin >> n >> m; //for input of N and M
int a[n][m];
for (int i = 0; i<n; i++) //for input of N integers of digit size M
for (int j = 0; j<m; j + >>
cin >> a[i][j];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
max = 0;
for (int k = 0; k<m; k++)
{
if (a[i][k] == 1 || a[j][k] == 1) max++;
cout << k;
if (k = m - 1 && max>max1) max1 = max;
if (k == m - 1 && max == max1) count++;;
}
}
}
cout << max1 << endl << count;
return 0;
}
I think the way of taking my input logic is wrong.could you please help me out.I am stuck in this question from 5 days.
PLease only help me on how should i take input and how to read the digit of integer.
Don't have a compiler with me so there's probably a syntax boner or two in there, but the logic walks through on paper.
Builds the storage:
std::cin >> n >> m; //for input of N and M
std::vector<std::vector<bool>>list(n,std::vector<bool>(m, false));
Loads the storage:
char temp;
for (int i = 0; i < n; i++) //for input of N integers of digit size M
{
for (int j = 0; j < m; j++)
{
std::cin >> temp;
if (temp == 1)
{
list[i][j] = true;
}
}
}
Runs the algorithm
for (int a = 0; a < n; a++)
{
for (int b = a+1; b < n; b++)
{
int knowcount = 0;
for (int j = 0; j < m; j++)
{
if (list[a][j] | list[b][j])
{
knowcount ++;
}
}
if (knowcount > max)
{
groupcount = 1;
max = know;
}
else if(knowcount == max)
{
groupcount ++;
}
}
}
Your method of input is wrong. According to your method, the input will have to be given like this (with spaces between individual numbers):
1 0 1 0 1
1 1 1 0 0
1 1 0 1 0
0 0 1 0 1
Only then it makes sense to create a matrix. But since the format in the question does not contain any space between a number in the same row, thus this method will fail. Taking into consideration the test case, you might be tempted to store the 'N' numbers in a single dimensional integer array, but keep in mind the constraints ('M' can be as big as 500 and int or even unsigned long long int data type cannot store such a big number).

Project Euler #10 How to pre-calculate sum of primes?

Here is the question:
The sum of the primes below 10 is 2+3+5+7=17.
Find the sum of all the primes not greater than given N.
Input Format :
The first line contains an integer T i.e. number of the test cases.
The next T lines will contains an integer N.
Output Format :
Print the value corresponding to each test case in seperate line.
Constraints :
1≤T≤104
1≤N≤106
https://www.hackerrank.com/contests/projecteuler/challenges/euler010
This is the link to the question.
So, i attempted to solve this question using sieve of Eratosthenes.
I pre calculated all primes below 10^6 which is the given limit for N.
6 out of the 7 test cases were accepted but the last test case give Timeout(TLE) .
I read the discussion forum and there they say that in order to solve the question we need to pre-calculate the sums of primes also.
So, i tried making an array of long long ints and tried storing all the sums in it. But this is giving me a segmentation fault.
So, how am I supposed to precalculate the sums of the primes?
Here is my code:
#include "header.h" //MAX is defined to be 1000000
bool sieve[MAX + 1]; // false = prime, true = composite
int main(void){
//0 and 1 are not primes
sieve[0] = sieve[1] = true;
//input limiting value
int n = MAX;
//cross out even numbers
for(int i = 4; i <= n; i += 2){
sieve[i] = true;
}
//use sieve of eratosthenes
for(int i = 3; i <= static_cast<int>(sqrt(n)); i += 2){
if(sieve[i] == false){
for(int j = i * i; j <= n; j += i)
sieve[j] = true;
}
}
long long p, ans = 0;
int t;
std::cin >> t;
while(t--){
std::cin >> p;
for(int i = 0; i <= p; ++i)
if(sieve[i] == false)
ans += i;
std::cout << ans << std::endl;
ans = 0;
}
return 0;
}
Given an array of primes prime[N], precomputing sums of primes can be done in a single for loop like this:
int sum[N];
sum[0] = primes[0];
for (int i = 1 ; i < N ; i++) {
sum[i] = prime[i]+sum[i-1];
}
You can use this array together with primes[] by running a binary search on primes, and picking the sum at the same position if the number being searched is prime, or at the prior position if the number is not prime.