Algorithm
Problem Name: beecrowd | 1149
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/1149
Summing Consecutive Integers
Adapted by Neilor Tonin, URI Brazil
Timelimit: 1
Write an algorithm to read a value A and a value N. Print the sum of N numbers from A (inclusive). While N is negative or ZERO, a new N (only N) must be read. All input values are in the same line.
Input
The input contains only integer values, can be positive or negative.
Output
The output contains only an integer value.
Input Sample | Output Sample |
3 2 |
7 |
3 -1 0 -2 2 |
7 |
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int main(){
int a, n;
cin >> a;
cin >> n;
while(n < = 0){ cin >> n;}
int sum = 0;
for (int i = 0; i < n; i++){
sum += i + a;
}
cout << sum << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int n = input.nextInt();
while(n < = 0){ n = input.nextInt();}
int sum = 0;
for (int i = 0; i < n; i++){
sum += i + a;
}
System.out.println(sum);
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
// var lines = input.split('\n');
var sep = [' ', '\n'];
// console.log(separators.join('|'));
var line = input.split(new RegExp(sep.join('|'), 'g'));
var a = parseInt(line.shift());
var n = parseInt(line.shift());
while(n < = 0){ n = parseInt(line.shift());}
var sum = 0;
for (var i = 0; i < n; i++){
sum += i + a;
}
console.log(sum);
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
list_num = list(map(int, input().split(" ")))
a = list_num[0]
n = 0
for i in range(1, len(list_num)):
k = list_num[i]
if (k > 0):
n = k
break
sum = 0
for i in range(n):
sum += i + a
print(sum)
Copy The Code &
Try With Live Editor
Input
Output