While Numbers from 10 sum until result is 1000 - c#

Hello my currenct code is doing sum on numbers after + including 10 I need it only after, now is doing like 10 + 10 = 20 then 20 +11 = 31 and etc which is wrong, when I change my i with 11 it adds 1 more interaction to the correct and makes the number more than 1000.
`` `
int i = 10;
int a = 10;
while (a < 1000)
{
a += i++;
}
Console.WriteLine(a);
Console.WriteLine(i);
Tried to change the numbers to 11 which is correct but gives me 1 more interaction which I want to remove!

sorry, do you mean to increment only by 10 ?, you can change a += i++; to a += i;

Solution:
int i = 11;
int a = 10;
while (a < 1000)
{
a += i++;
}
i -= 1;
a -= i;
Console.WriteLine(a);
Console.WriteLine(i);

So you want to termionate the loop before a gets > 1000.
The easiest way is to calculate the new value but not yet assign it to a:
int i = 10;
int a = 10;
while (a < 1000)
{
int newValue = a + i;
if (newValue > 1000) break;
i++;
a = newValue;
}
Console.WriteLine(a);
Console.WriteLine(i);
Alternative: you could also modify the while condition. As you know you are going to add i, check if the result would be still <= 1000:
while (a + i <= 1000)
{
a += i++;
}
Alternative 2: Another strategy proposed in #Slepcho's comment is to undo the last addition after the loop:
while (a <= 1000)
{
a += i++;
}
a -= --i;

Related

Digit sum in for loop C#

I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. I'd really appreciate help since I've been dwelling on this for a while now.
public static double number() {
Console.WriteLine("Enter your number! ");
string enter = Console.ReadLine();
double x = Convert.ToDouble(enter);
for (int i = 0; i < 1000; i++ ) {
double r;
double sum = 0;
while (i != 0) {
r = i % 10;
i = i / 10;
sum = sum + r;
}
if (sum == x) {
Console.WriteLine(i + " ");
}
}
return(0);
}
I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning.
I'd suggest trying to do something like this:
public static IEnumerable<int> number()
{
Console.WriteLine("Enter your number!");
string enter = Console.ReadLine();
int digitSum = int.Parse(enter);
foreach (var n in Enumerable.Range(0, 1000))
{
if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
{
yield return n;
}
}
}
When I run this and enter 6 then I get this result:
You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop.
You can fix this problem by saving a copy of i in another variable, say, in ii, and modifying it inside the while loop instead:
double r;
double sum = 0;
int ii = i;
while (ii != 0) {
r = iCopy % 10;
ii /= 10;
sum = sum + r;
}

Sum of numbers and cubing numbers in C#

Hey I am slightly new to C# it has been a week today. Ive managed to get this far but I cant seem to just out put the sum of the even numbers I've cubed i get the whole output and the last number is the total summed except i just want the last to show. Any help would be much appreciated and apologies for the horrendous code. Thanks
using System;
public class Test
{
public static void Main()
{
int j = 0; //Declaring + Assigning the interger j with 0
int Evennums = 0; // Declaring + Assigning the interger Evennums with 0
int Oddnums = 0; //Declaring + Assigning the interger Oddnums with 0
System.Console.WriteLine("Calculate the sum of all even numbers between 0 and the user’s number then cube it!"); //Telling console to write what is in ""
Console.WriteLine("Please enter a number");
uint i = uint.Parse(Console.ReadLine());
Console.WriteLine("You entered: " + i);
Console.WriteLine("Your number cubed: " + i*i*i);
if (i % 2 == 0)
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
Console.WriteLine("Even numbers summed together " + Evennums);
}
//increment j
j++;
}
else if(i%2 != 0)
//reset j to 0 like this: j=0;
j=0;
while (j<= i * i * i)
{
if (j%2 == 0)
{
Oddnums += j;
//Console.WriteLine(Oddnums);
}
//increment j
j++;
}
}
}
if you want to show the last sum, but not every summing process, change the location of print statement
if (i % 2 == 0)
{
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
}
//increment j
j++;
}
Console.WriteLine("Even numbers summed together " + Evennums);
}
same thing applies for the else if block.
You could try to achieve that you want like below, using LINQ:
// Calculate the cube of i.
int cube = i*i*i;
int sum = 0;
string message;
// Check if cube is even.
if(cube%2==0)
{
sum = Enumerable.Range(0,cube).Where(x => x%2==0).Sum();
message = "The sum of the even numbers in range [0,"+cube+"] is: ";
}
else // The cube is odd.
{
sum = Enumerable.Range(0,cube).Where(x => x%2==1).Sum();
message = "The sum of the odd numbers in range [0,"+cube+"] is: ";
}
// Print the sum.
Console.WriteLine(message+sum);

Largest Prime Factor algorithm optimization

I'm trying to improve this interesting algorithm as much as I can.
For now, I have this:
using System;
class Program
{
static void Main()
{
ulong num, largest_pFact;
uint i = 2;
string strNum;
Console.Write("Enter number: ");
strNum = Console.ReadLine();
num = ulong.Parse(strNum);
largest_pFact = num;
while (i < Math.Sqrt((double) largest_pFact))
{
if (i % 2 != 0 | i == 2) {
if (largest_pFact % i == 0)
largest_pFact /= i;
}
i++;
}
Console.WriteLine("Largest prime factor of {0} is: {1}", num, largest_pFact);
Console.ReadLine();
}
}
So any ideas?
Thanks!
EDIT: I implemented Ben's algorithm, thanks eveyone for your help!
I've got a faster algorithm here.
It eliminates the square root and handles repeated factors correctly.
Optimizing further:
static private ulong maxfactor (ulong n)
{
unchecked
{
while (n > 3 && 0 == (n & 1)) n >>= 1;
uint k = 3;
ulong k2 = 9;
ulong delta = 16;
while (k2 <= n)
{
if (n % k == 0)
{
n /= k;
}
else
{
k += 2;
if (k2 + delta < delta) return n;
k2 += delta;
delta += 8;
}
}
}
return n;
}
Here's a working demo: http://ideone.com/SIcIL
-Store Math.Sqrt((double) largest_pFact) in some variable, preferably a ulong. That avoids recalculating the function every pass through the loop, and integer comparison may be faster than floating-point comparisons. You will need to change the comparison to a <= though.
-Avoid looping on even numbers at all. Just include a special case for i=2, and then start with i at 3, incrementing by 2 on each loop. You can go even further by letting i=2,3 be special cases, and then only testing i = 6n+1 or 6n-1.
Well, first I would move the special case 2 out of the loop, there is no point in checking for that throughout the loop when it can be handled once. If possible use the data type int rather than uint, as it's generally faster:
if (largest_pFact % 2 == 0) {
largest_pFact /= 2;
}
int i = 3;
while (i < Math.Sqrt((double) largest_pFact)) {
if (i % 2 != 0) {
if (largest_pFact % i == 0) {
largest_pFact /= i;
}
}
i++;
}
The square root calculation is relatively expensive, so that should also be done beforehand:
if (largest_pFact % 2 == 0) {
largest_pFact /= 2;
}
int i = 3;
int sq = Math.Sqrt((double) largest_pFact);
while (i < sq) {
if (i % 2 != 0) {
if (largest_pFact % i == 0) {
largest_pFact /= i;
}
}
i++;
}
Then I would increment i in steps of two, to elliminate one modulo check:
if (largest_pFact % 2 == 0) {
largest_pFact /= 2;
}
int i = 3;
int sq = Math.Sqrt((double) largest_pFact);
while (i < sq) {
if (largest_pFact % i == 0) {
largest_pFact /= i;
}
i += 2;
}
To work, I believe that you need a while instead of an if inside the loop, otherwise it will skip factors that are repeated:
if (largest_pFact % 2 == 0) {
largest_pFact /= 2;
}
int i = 3;
int sq = Math.Sqrt((double) largest_pFact);
while (i < sq) {
while (largest_pFact % i == 0) {
largest_pFact /= i;
}
i += 2;
}
For one thing, you don't need to run Math.Sqrt on every iteration.
int root = Math.Sqrt((double) largest_pFact);
while (i < root)
{
if ((i % 2 != 0 | i == 2) && largest_pFact % i == 0) {
largest_pFact /= i;
root = Math.Sqrt((double) largest_pFact);
}
i++;
}
I think:
generate primes up to num/2
then check from largest to lowest if your num is divisible by the prime
would be faster.
edit num/2 NOT sqrt
It's always faster to look between sqrt(num) and 2 than it is to start at num/2. Every factor pair (besides the square-root one) has one number that is less than sqrt(num).
Ex: For 15, int(sqrt(15))==3
15/3=5, so you found the "5" factor by starting your testing at 3 instead of 7.

Sum of digits in C#

What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
You could do it arithmetically, without using a string:
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.
For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.
n = Math.Abs(n);
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.
public static int SumDigits(int value)
{
int sum = 0;
while (value != 0)
{
int rem;
value = Math.DivRem(value, 10, out rem);
sum += rem;
}
return sum;
}
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
I like the chaowman's response, but would do one change
int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)
I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.
I thought I'd just post this for completion's sake:
If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be
int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;
int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();
I would suggest that the easiest to read implementation would be something like:
public int sum(int number)
{
int ret = 0;
foreach (char c in Math.Abs(number).ToString())
ret += c - '0';
return ret;
}
This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.
I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.
private static int getDigitSum(int ds)
{
int dssum = 0;
while (ds > 0)
{
dssum += ds % 10;
ds /= 10;
if (dssum > 9)
{
dssum -= 9;
}
}
return dssum;
}
This is to provide the sum of digits between 0-9
public static int SumDigits1(int n)
{
int sum = 0;
int rem;
while (n != 0)
{
n = Math.DivRem(n, 10, out rem);
sum += rem;
}
return sum;
}
public static int SumDigits2(int n)
{
int sum = 0;
int rem;
for (sum = 0; n != 0; sum += rem)
n = Math.DivRem(n, 10, out rem);
return sum;
}
public static int SumDigits3(int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
Complete code in: https://dotnetfiddle.net/lwKHyA
int j, k = 1234;
for(j=0;j+=k%10,k/=10;);
A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc.
Hence I edited it, getting the digit sum correct each time with this code:
double a, n, sumD;
for (n = a; n > 0; sumD += n % 10, n /= 10);
int sumI = (int)Math.Floor(sumD);
where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.
static int SumOfDigits(int num)
{
string stringNum = num.ToString();
int sum = 0;
for (int i = 0; i < stringNum.Length; i++)
{
sum+= int.Parse(Convert.ToString(stringNum[i]));
}
return sum;
}
If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Please Input number");
Console.WriteLine(GetSum(Console.ReadLine()));
}
public static int GetSum(string num){
int summ = 0;
for(int i=0; i < num.Length; i++){
int currentNum;
if(int.TryParse(num[i].ToString(),out currentNum)){
if(currentNum % 2 == 1){
summ += currentNum;
}
}
}
return summ;
}
}
The simplest and easiest way would be using loops to find sum of digits.
int sum = 0;
int n = 1234;
while(n > 0)
{
sum += n%10;
n /= 10;
}
#include <stdio.h>
int main (void) {
int sum = 0;
int n;
printf("Enter ir num ");
scanf("%i", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("Sum of digits is %i\n", sum);
return 0;
}
Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.
string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

Modulus (%) in for-loop

I have a code here and I would like that it will display the first 10 and if I click on that, it will display again the second batch. I tried this first with my first for-code and it work now I'm working with arrays it seems it didn't accept it
The one I commented dont work? is this wrong?
Thanks
long [] potenzen = new long[32];
potenzen[0] = 1;
for (int i = 1; i < potenzen.Length; ++i)
{
potenzen[i] = potenzen[i-1] * 2;
//if (potenzen % 10 == 0)
// Console.ReadLine();
}
foreach (long elem in potenzen)
{
Console.WriteLine(" " + elem);
}
long [] potenzen = new long[32];
potenzen[0] = 1;
for (int i = 1; i < potenzen.Length; ++i)
{
potenzen[i]=potenzen[i-1]*2;
Console.WriteLine(potenzen[i-1]);
if (i % 10 == 0)
Console.ReadLine();
}
is more in line with what you want. An improvement would be to separate your data-manipulation logic from your data display logic.
long [] potenzen = new long[32];
potenzen[0] = 1;
for (int i = 1; i < potenzen.Length; ++i)
potenzen[i]=potenzen[i-1]*2;
for (int i = 0; i < potenzen.Length; ++i)
{
Console.WriteLine(potenzen[i]);
if (i % 10 == 0)
Console.ReadLine();
}
Of course, you could do this without an array
long potenzen = 1;
for (int i = 1; i < 32; ++i)
{
Console.WriteLine(potenzen);
potenzen = potenzen * 2;
if (i % 10 == 0)
Console.ReadLine();
}
You need:
if (i % 10 == 0)
and not:
if (potenzen % 10 == 0)
Applying the modulus operator to an array of longs is dubious.
potenzen is an array so you maybe try
if (i % 10 == 0)
or maybe
if (potenzen[i] % 10 == 0)
You're taking an array mod 10 -- at best, in an unsafe language, you'd be doing the modulo operation on a memory address.
This should work fine if you just change the line to:
// if you don't want to pause the first time you run it, replace with:
// if (i > 0 && i % 10 == 0) {
if (i % 10 == 0) {
Console.ReadLine();
}
Try changing it to:
long [] potenzen = new long[32];
potenzen[0] = 1;
Console.WriteLine(potenzen[0]);
for (int i = 1; i < potenzen.Length; ++i)
{
potenzen[i]=potenzen[i-1]*2;
Console.WriteLine(potenzen[i]);
if (i % 10 == 0)
{
var s = Console.ReadLine();
// break if s == some escape condition???
}
}
Right now, you're never printing, unless you completely finish your first for loop. My guess is that you're not allowing the full 32 elements to complete, so you're never seeing your results -
This will print them as they go.

Categories